How do i solve this situation?

1 回表示 (過去 30 日間)
MIHYUN
MIHYUN 2014 年 2 月 19 日
コメント済み: MIHYUN 2014 年 2 月 20 日
I have list of file like this.
trj.hst.00.+00
trj.hst.01.+00
trj.hst.02.+00
trj.hst.03.+00
...
So, I want to use while loop and The number of files is not fixed
I do not know whether to use some functions.
Are as follows: The code I wrote
c=0;
while (?)
file = sprintf('trj.hst.%02d.+00',c);
fid = fopen(file);
tline = fgetl(fid);
while ischar(tline)
matches = strfind(tline, '#');
num = length(matches);
if num > 0
tline = fgetl(fid);
else
B_temp = tline;
B = fscanf(fid, '%g %g %g %g %g %g %g %g', [8 inf]);
tline = fgetl(fid);
end
end
fclose(fid);
B2 = str2num(B_temp);
B = B';
res = [B2; B];
DATA(1,c).res = res;
% DATA.res_tline = B_temp;
c=c+1;
end
Thanks in advance.

採用された回答

Carsci
Carsci 2014 年 2 月 19 日
編集済み: Carsci 2014 年 2 月 19 日
Use the output fid (fileID) from fopen for your while condition. When the while loop gets to the end of the list, if the file does not exist then fopen cannot open the file and fileID is -1.
Only use the functions when fopen successfully opens a file, i.e. when it returns a file identifier greater >= 3
fid=0; c=0;
while fid ~= -1
file = sprintf('trj.hst.%02d.+00',c);
fid = fopen(file);
if fid < 3 continue; end
disp(['MIHYUN: Reading ' file])
tline = fgetl(fid);
while ischar(tline)
matches = strfind(tline, '#');
num = length(matches);
if num > 0
tline = fgetl(fid);
else
B_temp = tline;
B = fscanf(fid, '%g %g %g %g %g %g %g %g', [8 inf]);
tline = fgetl(fid);
end
end
fclose(fid);
B2 = str2num(B_temp);
B = B';
res = [B2; B];
DATA(1,c).res = res;
DATA.res_tline = B_temp;
c=c+1;
end
  1 件のコメント
MIHYUN
MIHYUN 2014 年 2 月 20 日
Thank you for your help!

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

その他の回答 (1 件)

Jos (10584)
Jos (10584) 2014 年 2 月 19 日
This problem is composed of smaller problems that you may or may not have solved. You can at least tackle them one by one
Problem 1 - How to get the list of files
You can collect them all at once using dir
Myfiles = dir('tr.hst.*.+00') ;
Problem 2 - Load a single file
filename = ...
fid = fopen(filename)
% load the data
res = % your code here
fclose(fid)
Problem 3 - Get the data of all the files
for k=1:numel(Myfiles)
filename = MyFiles(k).name ;
% code from problem 2 here
DATA(k).res = res ;
end

カテゴリ

Help Center および File ExchangeFile Operations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by