fprintf in a for loop

19 ビュー (過去 30 日間)
Vanessa Borgmann
Vanessa Borgmann 2019 年 3 月 12 日
コメント済み: Star Strider 2019 年 3 月 12 日
I wrote this function to write all numbers w(i) in a text document.
But as you can see the program only writes the last number w(12) = 2^12 in the document.
What can I do to get all w(i) into the document?
function test
N = 12;
k = 2;
for i = 1:N-1
w(i) = k^i;
w(i)
fid = fopen('Test2.txt', 'w');
fprintf(fid, '%s\n', 'Data w');
fprintf(fid, '%6.4f\t', w(i));
fclose(fid);
end
end
blabla.png

採用された回答

Star Strider
Star Strider 2019 年 3 月 12 日
I would do something like this:
N = 12;
k = 2;
for i = 1:N-1
w(i) = k^i;
w(i)
end
fid = fopen('Test2.txt', 'w');
fprintf(fid, '%s\n', 'Data w');
fprintf(fid, '%6.4f\n', w);
fclose(fid);
So save the intermediate results, and print everything to your file at the end.
  3 件のコメント
Guillaume
Guillaume 2019 年 3 月 12 日
Another option, is to write as you go along, as you've done. The problem with your code is that you opened and closed the file in the loop. Since you open the file with 'w' each step of the loop and since 'w' means open the file and replace everything in it, each step you completely overwrote what you wrote the previous step. Hence your result.
The simplest way to solve your problem would have been to replace the 'w' by an 'a' (ideally 'at') which means append instead of overwrite. That would still have been very inefficient as you would still open and close the file at each step. So either do it as Star did, write the whole lot at the end, or open the file before the loop, write in the loop and close the file after the loop:
N = 12;
k = 2;
fid = fopen('Test2.txt', 'wt'); %before the loop!
fprintf(fid, '%s\n', 'Data w'); %if that's supposed to be a header, it should go here, before the loop
for i = 1:N-1
w = k^i; %no need to index unless you want the w array at the end. In which case, it should be preallocated
fprintf(fid, '%6.4f\n', w);
end
fclose(fid); %after the loop!
Star Strider
Star Strider 2019 年 3 月 12 日
@Vanessa Borgmann —
If my Answer helped you solve your problem, please Accept it!
@Guillaume —
Thank you for your perceptive analysis and comments.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCell Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by