fprintf in a for loop
20 次查看(过去 30 天)
显示 更早的评论
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

0 个评论
采纳的回答
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
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
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 Exchange 中查找有关 Cell Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!