How to change the loop 'for' to 'while'?

1 回表示 (過去 30 日間)
MIHYUN
MIHYUN 2014 年 9 月 22 日
編集済み: Stephen23 2014 年 9 月 22 日
I have cord and files.
File names are {trj.hst.01.+00, trj.hst.02.+00, trj.hst.03.+00, ...}
And the cord is
for c=1:34
file = sprintf('trj.hst.%02d.+00',c);
fid = fopen(file);
tline = fgetl(fid);
...
c is 1 to 34. But the last number can be changed at any time .
So, I want to change loop 'for' to 'while'.
(There is also a file with a different name in the folder . like as {thm.hst.00.+00,thm.hst.01.+00..})
Please help me.
  1 件のコメント
Guillaume
Guillaume 2014 年 9 月 22 日
What do you mean can be changed at any time? Isn't it fixed once you call your program. If not, under what condition does it change?
As for the file with the different name, you actually haven't asked a question. What do you want to with it, open it at the same time as the trj file?

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

採用された回答

Stephen23
Stephen23 2014 年 9 月 22 日
編集済み: Stephen23 2014 年 9 月 22 日
MATLAB doesn't handle changes to a for loop variable easily, so your idea to use a while loop is ingenious. However I would suggest that you use a for loop anyway, which is a much more standard way of parsing multiple files in a loop using MATLAB. You will find some examples of how to do this here:
As you can see, the basic idea is dir to get a list of the files, and then read the files' data using the function of your choice, such as textscan, fgetl, fileread, etc.
If you really must use a while loop, then you could exist to check if the file really exists and to decide when the loop terminates (perhaps with a break). If you use exist, you will also need to use its second (optional) input.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLow-Level File I/O についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by