MATLAB: Aligning columns with fprintf

fprintfMATLAB

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:

Best Answer

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