how to read data file with rows of different length

23 次查看(过去 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

回答(2 个)

Azzi Abdelmalek
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

Image Analyst
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]

类别

Help CenterFile 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!

Translated by