how to read data file with rows of different length

22 ビュー (過去 30 日間)
esolve
esolve 2012 年 11 月 19 日
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 Center および File ExchangeLarge 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