Filter löschen
Filter löschen

problem with fprintf using two placeholders

2 Ansichten (letzte 30 Tage)
R2
R2 am 28 Apr. 2015
Bearbeitet: Stephen23 am 28 Apr. 2015
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?

Akzeptierte Antwort

Image Analyst
Image Analyst am 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 Kommentare
R2
R2 am 28 Apr. 2015
Worked perfectly! Thank you for also explaining it makes sense to me now!
Stephen23
Stephen23 am 28 Apr. 2015
Bearbeitet: Stephen23 am 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by