fprintf in a for loop

90 views (last 30 days)
Vanessa Borgmann
Vanessa Borgmann on 12 Mar 2019
Commented: Star Strider on 12 Mar 2019
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

Accepted Answer

Star Strider
Star Strider on 12 Mar 2019
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 Comments
Guillaume
Guillaume on 12 Mar 2019
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 on 12 Mar 2019
@Vanessa Borgmann —
If my Answer helped you solve your problem, please Accept it!
@Guillaume —
Thank you for your perceptive analysis and comments.

Sign in to comment.

More Answers (0)

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!