How to format an array so all numbers are the same length

I have a piece of code that outputs a table. I would like for the vertical lines of each column to line up but I don't know how to format the numbers so that they are all of the same length
| Volume | Mass | Force |
Tube A | 0.000216| 0.561 |5.4989|
Tube B | 0.000698| 1.815 |17.8038|
Tube C | 0.000477| 1.239 |12.1546|
Tube D | 0.000298| 0.774 |7.5933|

1 Comment

I guess that you use the function, fprintf(). Did you read the section on formatspec in the help of fprintf()?

Sign in to comment.

 Accepted Answer

For example,
A=rand(5).*randi(40,5);
T=num2str(A,' %.5f |'); T=[ repmat('| ', size(T,1),1) T];
disp ' ', disp(T), disp ' '
| 18.60161 | 11.15829 | 2.52174 | 6.47995 | 9.11992 | | 17.39329 | 24.35465 | 10.47445 | 31.09467 | 32.94388 | | 8.13919 | 0.79964 | 0.62663 | 21.73998 | 2.46469 | | 12.72383 | 6.08383 | 29.73448 | 0.33252 | 3.25479 | | 10.55642 | 14.51035 | 2.78072 | 8.72539 | 24.19349 |

More Answers (1)

data = repmat([0.01, 0.1, 1, 10, 1000], 2, 1);
fprintf(' |%8.6g| %-8.2f |\n', data)
| 0.01| 0.01 | | 0.1| 0.10 | | 1| 1.00 | | 10| 10.00 | | 1000| 1000.00 |

Categories

Products

Release

R2020b

Tags

Asked:

on 28 Mar 2021

Edited:

on 28 Mar 2021

Community Treasure Hunt

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

Start Hunting!