How to conditionally format a variable with fprintf
3 views (last 30 days)
Show older comments
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,
0 Comments
Answers (1)
Sulaymon Eshkabilov
on 7 Jul 2021
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);
See Also
Categories
Find more on Line Plots 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!