get error when inputting data from csv file line by line;
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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);
0 comentarios
Respuestas (1)
Walter Roberson
el 17 de Jul. de 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 comentarios
Walter Roberson
el 19 de Jul. de 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.
Ver también
Categorías
Más información sobre Spreadsheets en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!