printing string (from a cell array) and double array with fprintf
11 views (last 30 days)
Show older comments
got the following variables: lab is a cell array and vec_var is a double array
fprintf('%s\n', lab{:})
BHP
NAB
CSR
AGL
NCP
fprintf('%.4g\n', vec_var)
0.000324
0.000256
0.000484
0.001296
0.002304
trying to print as follows:
BHP = 0.000324
NAB = 0.000256
CSR = 0.000484
AGL = 0.001296
NCP = 0.002304
Tried several different fprintf statements, none give the output I want:
fprintf('%s\t = \t%.4g\n ', lab{:}, vec_var);
BHP = 78
AB = 67
SR = 65
GL = 78
CP = 0.000324
2.560000e-04 = 0.000484
1.296000e-03 = 0.002304
so far only the following came close:
for j=1:length(lab)
fprintf('%s = \t ', lab{j});
fprintf('%.4g', vec_var(j));
end
BHP =
0.000324
NAB =
0.000256
CSR =
0.000484
AGL =
0.001296
NCP =
0.002304
but with extra new lines (why?)
What's the best way to do this?
Thanks! Yudi
0 Comments
Answers (1)
Walter Roberson
on 19 Oct 2016
var_vec_cell = num2cell(vec_var);
data = [lab(:), var_vec_cell(:)] .'; %transpose is important
fprintf('%s\t = \t%.4g\n ', data{:})
4 Comments
Jon Martinez
on 25 May 2021
I know this is quite an old answer but I just wanted to say this post is pure gold. For the longest time I thought the only way to combine numbers and string with fprintf was with a loop and never ocurred to me to use cells. Hats off Mr. Roberson.
Paul Martin
on 9 Nov 2022
I agree with Jon that the post is pure gold.
Nevertheless it is worth while to point out that from R2016b you can use
compose
to get very similar functionality. I point this out because compose does not seem to be very well known: there are plenty of questions to uncle Google about sprintf and cell arrays but very few answers (none that I can find) mention compose.
See Also
Categories
Find more on Get Started with MuPAD in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!