how to print a table with hearders all aligned to the center of each column
7 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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
0 Kommentare
Antworten (2)
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);
1 Kommentar
Mathieu NOE
am 14 Apr. 2025
yet another functions you could be interested in...
Star Strider
am 14 Apr. 2025
x =1:5;
y= x.^2;
z = x*20;
xyz_table = table(x(:), y(:), z(:), VariableNames={'x-val1234','y-val123456','z-val1234567890'})
writetable(xyz_table, 'xyz_table.csv')
type('xyz_table.csv')
VN = xyz_table.Properties.VariableNames;
fprintf(['\n' repmat('\t%12s',1,3) '\n'], VN{:})
fprintf([repmat('\t\t%g',1,3) '\n'], table2array(xyz_table))
Just copy-pasting the table from the Command Window might be easiest, if you want to preserve the formatting.
.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Tables finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!