How to reduce \t commands

7 views (last 30 days)
TheSaint
TheSaint on 2 Feb 2024
Commented: William Rose on 3 Feb 2024
printf(' %1.0f \t\t %2.0f \t\t\t\t\t %0.2f\n', [F; SC; E])
Here is my current code. It works just fine, but in order for my table to be centered, I have to use multiple \t commands. Is there a way to clean this up, so I dont need so many \t commands?

Answers (2)

William Rose
William Rose on 2 Feb 2024
Hard to say, since we don't know what F and SC and E are.
You use the word table. Have you used Matlab's T=table(...) function? The default display format is different for tables, and there are different formatting options, than when you use fprintf() to display text and numeric data. If F, SC, E have same number of rows, you can do
F=(1:3)'; SC=["Me";"Myself";"I"]; E=(1:3)'/10;
T=table(F,SC,E);
disp(T)
F SC E _ ________ ___ 1 "Me" 0.1 2 "Myself" 0.2 3 "I" 0.3
and there are formatting options.
  2 Comments
TheSaint
TheSaint on 2 Feb 2024
Here is what F, SC, and E are
F = Matrix(1, : );
Unrecognized function or variable 'Matrix'.
SC = Matrix(2, : );
x = (F./SC);
E= (1/2).*(SC.*(x.^2));
William Rose
William Rose on 3 Feb 2024
Matrix=[100*cos(pi*(0:2)/10);100:100:300];
F = Matrix(1, : );
SC = Matrix(2, : );
x = (F./SC);
E= (1/2).*(SC.*(x.^2));
fprintf(' %1.0f \t\t %2.0f \t\t\t\t\t %0.2f\n', [F; SC; E])
100 100 50.00 95 200 22.61 81 300 10.91
I would stick with the fprintf() you originally posted, since it give the spacing which you said you prefer.

Sign in to comment.


Steven Lord
Steven Lord on 2 Feb 2024
Rather than trying to format your data in a tabular fashion yourself, have you considered putting your data in a table array and just displaying that table?
If you do have to set up the display yourself, you could use repmat and concatenate the text containing the tabs with the text containing the rest of the format.
five = repmat('\t', 1, 5)
five = '\t\t\t\t\t'
one = repmat('%d\t',1, 5)
one = '%d\t%d\t%d\t%d\t%d\t'
formatstring = ['%d' five '%d\n' one '%d\n']
formatstring = '%d\t\t\t\t\t%d\n%d\t%d\t%d\t%d\t%d\t%d\n'
The first part of formatstring will print the first two data values with 5 tabs between each one. Then the second part will print the next six data values with one tab between each value. So the first and third values will be lined up, as will the second and eighth, with the fourth through seventh equally spaced between the third and eighth.
fprintf(formatstring, 1:8)
1 2 3 4 5 6 7 8

Categories

Find more on Characters and Strings in Help Center and File Exchange

Tags

Products


Release

R2023b

Community Treasure Hunt

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

Start Hunting!