printing string (from a cell array) and double array with fprintf

10 ビュー (過去 30 日間)
yudi vass
yudi vass 2016 年 10 月 19 日
コメント済み: Paul Martin 2022 年 11 月 9 日
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

回答 (1 件)

Walter Roberson
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
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
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 ExchangeGet Started with MuPAD についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by