problem with fprintf using two placeholders

2 次查看(过去 30 天)
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?

采纳的回答

Image Analyst
Image Analyst 2015-4-28
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 个评论
R2
R2 2015-4-28
Worked perfectly! Thank you for also explaining it makes sense to me now!
Stephen23
Stephen23 2015-4-28
编辑:Stephen23 2015-4-28
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by