Search code examples
matlabmatlab-figurematlab-uitable

How to center-justify uitable columns in matlab?


How can I center-justify a column (strings and numbers) in a uitable? It's for presentation, so it is okay to "fake it" by padding it with spaces. (Using R2018a.)

% construct simple table as example %
t = array2table(zeros(4,1));
t.Properties.VariableNames{'Var1'} = 'id';
t.id(:) = 1;
t.fieldA = {'a'; 'b'; 'c'; 'd'};
t.GroupCount = [22; 1; 19; 0];

% plotting
f = figure;
uit = uitable(f, 'Data', table2cell(t));
uit.ColumnName={t.Properties.VariableNames{:}};
uit.RowName=[];

% test justification on the first column:
uit.ColumnFormat = {'numeric'}; % this right justifies
uit.ColumnFormat = {'char'}; % this left justifies
% how can I get it center justified?

Something like uit.ColumnFormat = {'%5s'}; but it can't pass this input (error below); is there a way to trick it?

Error setting property 'ColumnFormat' of class 'Table':
ColumnFormat definitions must be either 'numeric', 'logical', 'char', 'short', 'long', 'short e', 'long e', 'short g', 'long g', 'short eng', 'long eng',
'bank', '+', 'rat' or be a popupmenu definition

Solution

  • This can be done using an undocumented capability as follows:

    for k=1:numel(uit.Data)
        uit.Data{k} =['<html><tr><td width=9999 align=center>',num2str(uit.Data{k})];
    end
    

    Result: