fprintf within a for / if environment with crazy behaviour
1 view (last 30 days)
Show older comments
Harald von der Osten
on 9 Jun 2022
Commented: Harald von der Osten
on 9 Jun 2022
Using fprintf in a for / if environment (fileID = correct.XP0000020_0026.dat):
if ProfilKonst == 'X'
for i=1:length(x)
if x(i) == koordinate(1)
fprintf(fileID,'%.2f %.2f %.2f\n',[x(i) y(i) z(i)]);
end
end
end
the file 'correct.XP0000020_0026.dat' is empty, and the output on the console is:
correct.XP0000020_0026.datcorrect.XP0000020_0026.datcorrect.XP0000020_0026.datcorrect.XP0000020_0026.dat..........and so on
But when I use
fprintf('%.2f %.2f %.2f\n',[x(i) y(i) z(i)]);
everything is fine.
The file is opened with fopen(fileID,'wt'). I also tried to move fprintf in a function, but with the same result...
What is wrong? Thanks a lot.
0 Comments
Accepted Answer
Stephen23
on 9 Jun 2022
Edited: Stephen23
on 9 Jun 2022
The file is opened with fopen(fileID,'wt')"
Perhaps, but in any case, you did not provide the file identifier to FPRINTF.
"What is wrong?"
You did not provide a valid file identifier to FPRINTF. You are doing this:
fileID = 'correct.XP0000020_0026.dat';
fprintf(fileID,'%.2f %.2f %.2f\n',[x(i) y(i) z(i)])
% ^^^^^^ prints the filename
% ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ these are ignored
whereas what you need to do is get the identifier from FOPEN and use that:
fid = fopen(correct.XP0000020_0026.dat','wt');
fprintf(fid,'%.2f %.2f %.2f\n',[x(i) y(i) z(i)])
fclose(fid);
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!