Multiple outputs by a loop

1 回表示 (過去 30 日間)
Ivan Mich
Ivan Mich 2020 年 5 月 16 日
コメント済み: Stephen23 2020 年 5 月 16 日
Hello, I have a question. I would like to create multiple files(outputs) by a loop. File parameters.txt has two lines. I would like to create files with name output1 and output2, by a loop. My commands are these:
Param=regexp(fileread('parameters.txt'), '\r?\n', 'split') .';
for i=1:size()
fid = fopen( 'output%d', 'w');
fprintf(fid,'%s\n')
fclose(fid)
end
But I do not know how to make it . Could you help me?
  1 件のコメント
Stephen23
Stephen23 2020 年 5 月 16 日
Note that with out a third (or more) input argument this will not print anything:
fprintf(fid,'%s\n')

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

回答 (2 件)

Ajay Kumar
Ajay Kumar 2020 年 5 月 16 日
編集済み: Ajay Kumar 2020 年 5 月 16 日
Param=regexp(fileread('parameters.txt'), '\r?\n', 'split') .';
for i=1:size()
fid = fopen( ['output',i,'.txt'], 'w');
fprintf(fid,'%s\n')
fclose(fid)
end
  1 件のコメント
Stephen23
Stephen23 2020 年 5 月 16 日
This will not work as expected.
Lets look at the actual output character vector when i=1:
>> i = 1;
>> double(['output',i])
ans =
111 117 116 112 117 116 1
Those are the printable characters 'o', 'u', 't', 'p', 'u' and 't', followed by the unprintable "Start of Heading" control character. I doubt that that is very useful, or intended.

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


Stephen23
Stephen23 2020 年 5 月 16 日
編集済み: Stephen23 2020 年 5 月 16 日
Replace the fopen with these two lines:
fnm = sprintf('output%d.txt',i);
fid = fopen(fnm,'wt');
  2 件のコメント
Ivan Mich
Ivan Mich 2020 年 5 月 16 日
OK, but in this code I am making some calculations. I want in these two output files to be contented the result of these calculations.
How could I do this?
Stephen23
Stephen23 2020 年 5 月 16 日
"How could I do this?"
This is very general question: it is not clear which of the many steps involved you are asking about.
You don't explain what "calculations" are involved, so clearly I can't help with that. You don't even say what class or size the data arrays are, so I can't help you with selecting a suitable method to save your data.
If you want to export multiple files in a loop then you should pick a suitable function (which might be fprintf as your question shows):
and follow the examples here
Read the sprintf documentation to know how to specify the format string for the filenames:
Read the size documentation to know how to measure the dimensions of an array:

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

カテゴリ

Help Center および File ExchangeWorkspace Variables and MAT-Files についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by