フィルターのクリア

problem with fprintf using two placeholders

2 ビュー (過去 30 日間)
R2
R2 2015 年 4 月 28 日
編集済み: Stephen23 2015 年 4 月 28 日
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 Center および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by