printing string (from a cell array) and double array with fprintf
10 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Walter Roberson
2016-10-19
var_vec_cell = num2cell(vec_var);
data = [lab(:), var_vec_cell(:)] .'; %transpose is important
fprintf('%s\t = \t%.4g\n ', data{:})
4 个评论
Jon Martinez
2021-5-25
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
2022-11-9
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Get Started with MuPAD 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!