Aligning columns with fprintf

29 vues (au cours des 30 derniers jours)
Matthew Covington
Matthew Covington le 26 Août 2020
Commenté : Matthew Covington le 27 Août 2020
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:

Réponse acceptée

Stephen23
Stephen23 le 27 Août 2020
Modifié(e) : Stephen23 le 27 Août 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 commentaire
Matthew Covington
Matthew Covington le 27 Août 2020
Thank you! This worked exactly as I had hoped.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Tags

Produits


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by