get error when inputting data from csv file line by line;
조회 수: 2 (최근 30일)
이전 댓글 표시
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
답변 (1개)
Walter Roberson
2012년 7월 17일
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
Walter Roberson
2012년 7월 19일
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!