how to print a table with hearders all aligned to the center of each column

7 Ansichten (letzte 30 Tage)
hello,
I am trying to print a table with headers of different lengths and numbers with different precision. all aligned to the center of the column and with a separation line that starts with the first characte of the first header and end with the last character of the last header.
this is the code I have for now:
x =1:5;
y= x.^2;
z = x*20;
table =[x; y; z];
t=strings(3);
t(1)=' x-val1234';
t(2)=' y-val123456';
t(3)=' z-val1234567890';
% pp=strcat(t(1),',',t(2),',',t(3));
pp=strcat(t(1),t(2),t(3),'\n');
fprintf(pp)
fprintf('--------------------------------\n')
fprintf('%8.2f %10.1f %12.2f\n', table)
an this is the output I get
x-val1234 y-val123456 z-val1234567890
--------------------------------
1.00 1.0 20.00
2.00 4.0 40.00
3.00 9.0 60.00
4.00 16.0 80.00
5.00 25.0 100.00
what I would like to get is this:
x-val1234 y-val123456 z-val1234567890
-----------------------------------------------
1.00 1.0 20.00
2.00 4.0 40.00
3.00 9.0 60.00
4.00 16.0 80.00
5.00 25.0 100.00

Antworten (2)

Mathieu NOE
Mathieu NOE am 14 Apr. 2025
see attached a nice formatting piece of code for this job
example code :
data = 1e2.*rand(5,4);
fmt = {'%.3g'};
col_headers = {'a','b','c','d'};
row_headers = {'No.','1','2','3','4','5'};
out = print_table(data,fmt,col_headers,row_headers)
% save to file
filename = 'exp.txt';
fileID = fopen(filename,'w');
fprintf(fileID,out);
fclose(fileID);

Star Strider
Star Strider am 14 Apr. 2025
The easiest way is to use a table array.
x =1:5;
y= x.^2;
z = x*20;
xyz_table = table(x(:), y(:), z(:), VariableNames={'x-val1234','y-val123456','z-val1234567890'})
xyz_table = 5x3 table
x-val1234 y-val123456 z-val1234567890 _________ ___________ _______________ 1 1 20 2 4 40 3 9 60 4 16 80 5 25 100
writetable(xyz_table, 'xyz_table.csv')
type('xyz_table.csv')
x-val1234,y-val123456,z-val1234567890 1,1,20 2,4,40 3,9,60 4,16,80 5,25,100
VN = xyz_table.Properties.VariableNames;
fprintf(['\n' repmat('\t%12s',1,3) '\n'], VN{:})
x-val1234 y-val123456 z-val1234567890
fprintf([repmat('\t\t%g',1,3) '\n'], table2array(xyz_table))
1 2 3 4 5 1 4 9 16 25 20 40 60 80 100
Just copy-pasting the table from the Command Window might be easiest, if you want to preserve the formatting.
.

Kategorien

Mehr zu Tables finden Sie in Help Center und File Exchange

Produkte


Version

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by