fprintf loop with vector and cell array

3 visualizzazioni (ultimi 30 giorni)
I want to output the results of solving a linear system as sentences like
The value of p2 is bla Pa.
The value of p3 is blabla Pa.
.
.
.
The value of v49 is bla m/s.
The units could be a little difficult to get into one fprintf loop so let's first focus on getting the numbers. Since vectors didn't seem to work, I tried cell arrays like
variables={'p2';'p3';'p4';'p5';'v12';'v23';'v24';'v34';'v35';'v45';'v36';'v57';'v58';'v49'};
fprintf('The value of %s is %f',variables{1:end},x);
But the output was
The value of p2 is 112.000000The value of 3 is 112.000000The value of 4 is 112.000000The value of 5 is 118.000000The value of 12 is 118.000000The value of 23 is 118.000000The value of 24 is 118.000000The value of 34 is 118.000000The value of 35 is 118.000000The value of 45 is 118.000000The value of 36 is 118.000000The value of 57 is 118.000000The value of 58 is 118.000000The value of 49 is 133.626165The value of 5494857740200/33009242941 is 166.464216The value of 5160268719550/33009242941 is -0.105082The value of -10839592125/132036971764 is -0.082095The value of 0 is 0.025341The value of 6691780413/264073943528 is -0.084887The value of 660916584/33009242941 is 0.020022The value of -2802070584/33009242941 is >>
Not sure what went wrong. My x, by the way, is this vector
133.6262
166.4642
166.4642
156.3280
-0.1051
-0.0821
-0.0821
0
0.0253
0.0253
-0.0849
0.0200
0.0200
-0.0849
I could try this but it uses vectors and not cell arrays which seems difficult because then MATLAB concatenates all my strings into one huge string like p2p3p4...
https://www.mathworks.com/help/matlab/ref/fprintf.html

Risposta accettata

Star Strider
Star Strider il 14 Ott 2016
To print variables of different data types, it has always been my experience that an explicit (or implied) loop is necessary:
for k1 = 1:size(x,1);
fprintf('The value of %s is %.4f\n',variables{k1},x(k1));
end
You also need an end-of-line terminator '\n'. I added it.

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by