Create table from structure - alignment

1 回表示 (過去 30 日間)
Alessandro D
Alessandro D 2021 年 6 月 1 日
回答済み: Stephen23 2021 年 6 月 2 日
I have a structure with scalar fields, say mom, and I would like to display the values of the structure on the screen in aligned columns, possibly with some header. Here is a minimum working example:
mom.a = 1;
mom.b = 2;
mom.veryLongName = 3;
header = {'Moment'; 'Value'};
fnames = fieldnames(mom);
pvec = zeros(numel(fnames),1);
for i = 1:numel(fnames)
pvec(i) = mom.(fnames{i});
end
fprintf('%s \t \t %s \n',header{1},header{2});
for i = 1:numel(fnames)
fprintf('%s \t \t %8.3f \n',fnames{i},pvec(i));
end
This code works OK but the problem is that columns are not aligned, especially if a field has a very long name. This is the output:
Moment Value
a 1.000
b 2.000
veryLongName 3.000
Any suggestion is appreciated!

採用された回答

Stephen23
Stephen23 2021 年 6 月 2 日
Simpler:
mom.a = 1;
mom.b = 2;
mom.veryLongName = 3;
hdr = {'Moment'; 'Value'};
tmp = [fieldnames(mom),struct2cell(mom)].';
fprintf(' %-20s %-s\n', hdr{:});
Moment Value
fprintf(' %-20s %-8.3f\n', tmp{:});
a 1.000 b 2.000 veryLongName 3.000

その他の回答 (1 件)

per isakson
per isakson 2021 年 6 月 2 日
編集済み: per isakson 2021 年 6 月 2 日
I've modified the format specifier.
%%
mom.a = 1;
mom.b = 2;
mom.veryLongName = 3;
header = {'Moment'; 'Value'};
fnames = fieldnames(mom);
pvec = zeros(numel(fnames),1);
for i = 1:numel(fnames)
pvec(i) = mom.(fnames{i});
end
%%
name_len = max( [ strlength(header(1)); cellfun( @strlength, fnames ) ] ) + 2;
%%
fprintf( '%-*s%8s\n', name_len, header{1}, header{2} );
Moment Value
for i = 1:numel(fnames)
fprintf( '%-*s%8.3f\n', name_len, fnames{i}, pvec(i) );
end
a 1.000 b 2.000 veryLongName 3.000
Two thirds down the page fprintf, Write data to text file you find the description of this use of the format specifier. Search for the subsection "Field Width"

カテゴリ

Help Center および File ExchangeImport, Export, and Conversion についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by