problem with fprintf using two placeholders

18 views (last 30 days)
I have written this bit of code to create a macro and write some text to it with two place holders.
ap=1:20
jap = 80:100
fid = fopen('test.mac', 'w');
fprintf(fid,'some text %d and other value %d \n',ap, jap);
fclose(fid);
I hoped this would place the value of ap in the first placeholder and jap in the second placeholder, but instead it gives me lines where both placeholders are filled with ap then after filling all the values of ap, it gives lines with jap. Any idea how I can fix this?

Accepted Answer

Image Analyst
Image Analyst on 28 Apr 2015
No, because they're not single values - they're arrays. So it puts the first two values of ap in the place of %d, then it "reuses" the format string and the elements 3 and 4 will go into it the next time, and so on until ap has used all of its values. To do one ap and then one jap, you will need to use a loop:
for k = 1 : length(ap)
fprintf(fid,'Some text %d and other value %d.\n',ap(k), jap(k));
end
  2 Comments
R2
R2 on 28 Apr 2015
Worked perfectly! Thank you for also explaining it makes sense to me now!
Stephen23
Stephen23 on 28 Apr 2015
Edited: Stephen23 on 28 Apr 2015
Actually you do not "need to use a loop" at all. Simply concatenate the vectors vertically, and let fprintf do all the work for you:
ap=1:20;
jap = 80:99;
fid = fopen('temp.txt', 'wt');
fprintf(fid,'Some text %d and other value %d.\n',[ap;jap]);
fclose(fid);
produces exactly the same result and is faster too! This uses exactly the behavior that Image Analyst explains in their answer.

Sign in to comment.

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!