Create table from structure in matlab - alignment

Viewed 35

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 
1 Answers

You can convert the struct to a table, and let MATLAB format the display for you:

disp(struct2table(mom))

output:

    a    b    veryLongName
    _    _    ____________

    1    2    3           

Alternatively, use the field width specifier for the fprintf format string:

width = max(cellfun('length', fnames));
width = max(width, length(header{1}));
fprintf('%-*s   %s\n', width, header{1}, header{2});
for i = 1:numel(fnames)
    fprintf('%-*s   %-8.3f\n', width, fnames{i}, mom.(fnames{i}));
end

output:

Moment         Value
a              1.000   
b              2.000   
veryLongName   3.000   

%-*s is the same as %s, but with an - flag to indicate left-alignment, and the * width specifier, which indicates getting the width from a parameter. So %-*s reads two values from the parameters: first a width, then a string.

Related