how to read data file with rows of different length
조회 수: 20 (최근 30일)
이전 댓글 표시
I have a file, each row has different number of numbers, like
1 2 2 3
12 3 4 5 5 9
1 3
0.5 0.002 0.02
I tried importdata, but it seems to divide a row into two rows any other methods? thanks
댓글 수: 0
답변 (2개)
Azzi Abdelmalek
2012년 11월 19일
편집: Azzi Abdelmalek
2012년 11월 19일
fid = fopen('file1.txt');
line1 = fgetl(fid);
res=line1;
while ischar(line1)
line1 = fgetl(fid);
res =char(res,line1)
end
fclose(fid);
for k=1:size(res,1)
A{k}=str2num(res(k,:))
end
댓글 수: 0
Image Analyst
2012년 11월 19일
Try this:
fid = fopen('data.txt');
textLine = fgets(fid); % Read first line.
lineCounter = 1;
while ischar(textLine)
fprintf('\nLine #%d of text = %s\n', lineCounter, textLine);
% get into numbers array.
numbers = sscanf(textLine, '%f ')
% Put numbers into a cell array IF and only if
% you need them after the loop has exited.
% First method - each number in one cell.
for k = 1 : length(numbers)
ca{lineCounter, k} = numbers(k);
end
% ALternate way where the whole array is in one cell.
ca2{lineCounter} = numbers;
% Read the next line.
textLine = fgets(fid);
lineCounter = lineCounter + 1;
end
fclose(fid);
% Display the cell arrays in the command line.
ca
ca2
In the command window:
ca =
[ 1] [ 2] [ 2] [3] [] []
[ 12] [ 3] [ 4] [5] [5] [9]
[ 1] [ 3] [] [] [] []
[0.5] [0.002] [0.02] [] [] []
ca2 =
[4x1 double] [6x1 double] [2x1 double] [3x1 double]
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Large Files and Big Data에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!