Aligning columns with fprintf

37 次查看(过去 30 天)
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:

采纳的回答

Stephen23
Stephen23 2020-8-27
编辑:Stephen23 2020-8-27
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Startup and Shutdown 的更多信息

标签

产品


版本

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by