how to read data file with rows of different length

22 Ansichten (letzte 30 Tage)
esolve
esolve am 19 Nov. 2012
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

Antworten (2)

Azzi Abdelmalek
Azzi Abdelmalek am 19 Nov. 2012
Bearbeitet: Azzi Abdelmalek am 19 Nov. 2012
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 am 19 Nov. 2012
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]

Kategorien

Mehr zu Large Files and Big Data finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by