Is it possible to scan a group of lines in MATLAB?

1 回表示 (過去 30 日間)
Brian
Brian 2013 年 9 月 11 日
I have a textfile I would like to pull data from. Rather than reading line by line I would like to just have it scan my textfile in chunks. For example scanning it every 10 lines. Then I intend to write some of the data from these 10 lines to a new file and read the next 10 lines. Is this possible?

採用された回答

Jan
Jan 2013 年 9 月 12 日
I do not see the general difference between scanning a file line by line or in blocks of 10 lines.
fid = fopen(FileName, 'r');
if fid == -1, error('Cannot open file: %s', FileName);
k = 0;
C = {};
D = cell(1, 10);
proceed = true;
while 1
for m = 1:10
s = fgetl(fid);
if ~ischar(s)
proceed = false;
D = D(1:m);
break;
end
D{m} = s;
end
k = k + 1;
C{k} = D;
end
Instead of storing D in C, you can parse it how ever you like.
This wooden technique is efficient, when you do not have to keep all lines in the memory at once (omit everything concerning "C" then). textscan looks much nicer, but is not necessarily faster.

その他の回答 (2 件)

Walter Roberson
Walter Roberson 2013 年 9 月 11 日
Yes. After the format specifier, in the next parameter put the number of times you want the format to be reused. 10 for example if the format is for one line's worth of information.

sanky kumar
sanky kumar 2013 年 9 月 11 日
hi brian
you can use textscan.
C = textscan(fileID,formatSpec) reads data from an open text file into cell array, C. The text file is indicated by the file identifier, fileID. Use fopen to open the file and obtain the fileID value. When you finish reading from a file, close the file by calling fclose(fileID).
textscan attempts to match the data in the file to formatSpec, which is a string of conversion specifiers.
  1 件のコメント
Brian
Brian 2013 年 9 月 11 日
So for example, would I put
textscan('example.txt',10);
and if I wanted to read specific data on the line I would add %f after 10?
textscan('example.txt',10,%f)

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeText Files についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by