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

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);

Respuestas (1)

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

Ken
Ken el 17 de Jul. de 2012
Walter, thanks for your quick reply. But when I used NET(end+1) = line; I got: ??? The following error occurred converting from cell to double: Error using ==> double Conversion to double from cell is not possible.
I am quite new to Matlab. Does this causes by using csv2cell()?
Initialize
NET = {};
Ken
Ken el 19 de Jul. de 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?
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.

Iniciar sesión para comentar.

Categorías

Más información sobre Get Started with MATLAB en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

Ken
el 17 de Jul. de 2012

Community Treasure Hunt

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

Start Hunting!

Translated by