MatLab - Importing CSV text file that contains commas not meant to separate -
uh! have received delivery of large text files comma separated value format. need build struct each file data analysis. piece of cake! have done before. wrote code build structs. eventually, discovered there can case data has comma the real data, not meant separate data. caught before leaving work. working home now, hoping derive solution or have recommended solution posting here. (below code , data file example). appreciate help, comments, solutions, and/or feedback. thanks
data file example(line 5 problem begins, 'bubba1, ttr1' should not separated):
chan, date, time, signalname, mode#, lat, long,
01, 12/12/12, 01:01:20.234, off, 0, 39.185, -106.85,
01, 12/12/12, 01:01:20.345, off, 0, 39.185, -106.85,
01, 12/12/12, 01:01:20.445, off, 0, 39.185, -106.85,
01, 12/12/12, 01:01:20.545, bubba1, ttr1, 1, 39.185, -106.85,
01, 12/12/12, 01:01:20.645, bubba1, ttr1, 1, 39.185, -106.85,
01, 12/12/12, 01:01:20.745, bubba1, ttr1, 1, 39.185, -106.85,
01, 12/12/12, 01:01:20.845, off, 0, 39.185, -106.85,
my code:
clear;clc; fid = fopen('test.txt'); fileheader = textscan(fid,'%s',1,'delimiter','\n','headerlines',0); fileheader = strread(char(fileheader{:}),'%s','delimiter',',')'; fileheader = strrep(fileheader,' ',''); fileheaderlength=length(fileheader); format = repmat('%s',1,fileheaderlength); data = textscan(fid,format,'delimiter',','); data=[data{:}];
i think case need if statement , while loop it. commas @ end of line make more complicated.
clear;clc; fid = fopen('test.txt'); fileheader = textscan(fid,'%s',1,'delimiter','\n','headerlines',0); fileheader = strread(char(fileheader{:}),'%s','delimiter',',')'; fileheader = strrep(fileheader,' ',''); data = fileheader; line = {''}; while ~isempty(line) line = textscan(fid,'%s',1,'delimiter','\n','headerlines',0); line = strread(char(line{:}),'%s','delimiter',',')'; if length(line) > length(fileheader) line = {line{1:3}, strjoin(line(4:end-3), ', '), line{end-2:end}}; end data=vertcat(data, line); end fclose(fid);
Comments
Post a Comment