필터 지우기
필터 지우기

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

조회 수: 2 (최근 30일)
Ken
Ken 2012년 7월 17일
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);

답변 (1개)

Walter Roberson
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
Ken
Ken 2012년 7월 19일
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 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 CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by