Azzera filtri
Azzera filtri

problem with fprintf using two placeholders

2 visualizzazioni (ultimi 30 giorni)
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?

Risposta accettata

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

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Characters and Strings in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by