Aligning columns with fprintf

32 views (last 30 days)
All of my data is correct, however I cannot figure out how to format the top numbers correctly. The only problem I am having is I do not know how to align the numbers correctly without adding a decimal value. I would like to know how to align the whole numbers, like 1.0 and 2.0, without the 0 in the decimal place. I know %2.1f adds a number behind the decimal automatically, but could someone show me how I could align them without a deciamal behind whole numbers? Below is my code and a picture of my output. Keep in mind this is in a for loop.
fprintf('%2.1f ',incWater(numCol+1))
This is what my code is supposed to look like:

Accepted Answer

Stephen23
Stephen23 on 27 Aug 2020
Edited: Stephen23 on 27 Aug 2020
You can use '%g' to print values with trailing zeros removed:
X = 0.5:0.5:2.5;
Y = 500:250:1500;
M = [425,1441,2651,3665,4091;638,2160,3976,5498,6136;851,2880,5301,7330,8181;1064,3600,6627,9163,10227;1276,4320,7952,10996,12272];
N = numel(X);
F = repmat('%8.2g',1,N);
fprintf(sprintf(' %s\n',F),X)
F = repmat('%8.0f',1,1+numel(X));
fprintf(sprintf('%s\n',F),[Y;M.'])
Prints:
0.5 1 1.5 2 2.5
500 425 1441 2651 3665 4091
750 638 2160 3976 5498 6136
1000 851 2880 5301 7330 8181
1250 1064 3600 6627 9163 10227
1500 1276 4320 7952 10996 12272
  1 Comment
Matthew Covington
Matthew Covington on 27 Aug 2020
Thank you! This worked exactly as I had hoped.

Sign in to comment.

More Answers (0)

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Tags

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!