How to conditionally format a variable with fprintf

3 ビュー (過去 30 日間)
Blue
Blue 2021 年 7 月 7 日
コメント済み: Blue 2021 年 7 月 7 日
Hi,
Quick question: a want to contionally format a variable so that there are 2 decimals for all numbers except for 0; 0 should be 0, not 0.00. What would be the easiest way to do that ?
T = table([1.16666, 2.16666, 3.16666, 0, 0]');
T_names = T.Properties.VariableNames;
y = table2cell(T).';
fid = fopen('test.txt','wt');
fprintf(fid, '%s\n', T_names{:});
fprintf(fid, '%.2f\n', y{:});
fclose(fid);
Thank you,

回答 (1 件)

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2021 年 7 月 7 日
Hi,
Here is an easy solution with if cond operator:
...
fprintf(fid, '%s\n', T_names{:});
for ii=1:numel(y)
if y{ii}~=0
fprintf(fid, '%.2f\n', y{ii});
else
fprintf(fid, '%1.0f\n', y{ii});
end
end
fclose(fid);
  1 件のコメント
Blue
Blue 2021 年 7 月 7 日
Yes, thank you, but what if I have many variables and I want to contionally format several of them, say variables T.d and T.h ?
a = {'C1', 'A1', 'B1'}'
b = {'C', 'A', 'B'}'
c = {1.1, 2.1, 3.1}'
d = {1.16666, 2.16666, 0}'
e = {'C', 'A', 'B'}'
f = {'C', 'A', 'B'}'
g = {1.1, 2.1, 3.1}'
h = {1.16666, 2.16666, 0}'
T = table(a, b, c, d, e, f, g, h);
T_names = T.Properties.VariableNames;
y = table2cell(T);
fid = fopen('test.txt','wt');
fprintf(fid, '%s;%s;%s;%s;%s;%s;%s;%s;\n', T_names{:});
fprintf(fid, '%s;%s;%.1f;%.2f;%s;%s;%.1f;%.2f;\n', y{:});
fclose(fid);

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

タグ

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by