Clear Filters
Clear Filters

get error when inputting data from csv file line by line;

2 views (last 30 days)
Hello!
I tried to read a double-quoted csv file. This csv file was not in a good shape. It had multiple headers, blanks lines above the data part, so I have to do data input line by line.
CSV data looks like:
-------------------------------------------------------
"date:", "XX XX"
"Operator:", "XXXX"
" "
"XXXXXXXX", "XXXX", "YYYY", "NNNN"
"DataType", "NET"
"a", "b", "c", "d", .. "e"
"1", "2", "2", "3", .. "1"
"2", "2", "2", "3", .. "1"
"3", "3", "2", "3", .. "1"
"4", "2", "6", "3", .. "0"
"5", "2", "2", "3", .. "1"
...
" "
"other", "other"
...
----------------------------------------
My code starts reading data into variable 'NET' when the 1st column is a 'DataType' plus the 2nd colum is a 'NET'. (please see the following code).
variable 'NET' was set to [ ] by default (code: NET=[ ]). But when I use ( NET=[NET; line]; ), I got the following error:
??? Error using ==> vertcat
CAT arguments dimensions are not consistent .
I think I made mistakes in my code, but did not know how to fix it. Any help?
Thanks!!
%code ------------------------------------------------;
fid_t = fopen(...
'C:datafile.csv', 'r');
while ~feof(fid_t)
temp1 = fgetl(fid_t);
temp2 = regexprep(temp1, '"', '');
line = csv2cell(temp2);
if strcmp(line{1}, 'DataType:')
if strcmp(line{2}, 'Net')
O2=line{2};
fgetl(fid_t);
NET=[];
while ~feof(fid_t)
tp1 = fgetl(fid_t);
tp2 = regexprep(tp1, '"', '');
line = csv2cell(tp2);
if isempty(line)
break;
end
NET=[NET; line];
end
end
end
end;
fclose(fid_t);

Answers (1)

Walter Roberson
Walter Roberson on 17 Jul 2012
When you get near the bottom, "line" will not have as many fields, and you will be trying to vertcat() together two cell arrays with different number of columns.
Change
NET=[NET; line];
to
NET(end+1) = line;
and you will instead build up NET as a cell array row vector each element of which is a cell produced by csv2cell().
  4 Comments
Ken
Ken on 19 Jul 2012
Walter, after using NET={}; I got:
??? Subscripted assignment dimension mismatch.
I think I have trouble initializing 'cell'. Is it possible to initialize "NET={}" then use "NET(end+i)=line" to change NET's dimension repeatedly?
Walter Roberson
Walter Roberson on 19 Jul 2012
Yes, that should be okay, other than using end+1 instead of end+i. Provided, that is, that csv2cell() really does return a cell array.

Sign in to comment.

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!