printing string (from a cell array) and double array with fprintf
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
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
yudi vass
on 20 Oct 2016
Guillaume
on 20 Oct 2016
The data{:} expansion in Walter's answer is equivalent to:
fprintf(%s\t = \t%.4g\n ', data{1}, data{2}, data{3}, ..., data{end})
fprintf just feeds its inputs in order to the formatting codes. If there's more input arguments than formatting codes, it just restart from the start of the format string until it's consumed all inputs.
Therefore you want data{1} to be lab{1}, data{2} to be var_vec_cell{1}, data{3} to be lab{3}, etc. The concatenation plus transpose just ensures that you obtain this mapping.
Another way of creating data would be:
data = [reshape(lab, 1, []); reshape(var_vec_cell, 1, [])];
Walter's way is just less characters to type (at the expense of more reshaping/transposition)
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.
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!