how to read data file with rows of different length

22 visualizaciones (últimos 30 días)
esolve
esolve el 19 de Nov. de 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

Respuestas (2)

Azzi Abdelmalek
Azzi Abdelmalek el 19 de Nov. de 2012
Editada: Azzi Abdelmalek el 19 de Nov. de 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 el 19 de Nov. de 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]

Categorías

Más información sobre Large Files and Big Data en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by