MATLAB: How to format the number displayed on the “uitable” in App Designer

cellsdecimaldigitsformattingMATLABspecificuitable

How do I format the number displayed on the "uitable" in App Designer?

Best Answer

There are three workarounds.
1. Use "format" function
You can specify the format of the displayed numbers using the "format" function.
For example:
% Specify the format using 'format' function
format short e
data(:,1)=num2cell((1:10)');
rng(1);
data(:,2)=num2cell(rand(10,1)*1e5);
% Assign data to the table

app.UITable.Data=data;
The format is specified as "short e". The numbers are displayed with short scientific notation with 4 digits after the decimal point.
Please see the attached file "UseFormat.mlapp" for the full example.
For more information about the 'format' function:
2. Use "sprintf" function
If you want to have more control on how the number is displayed, you can use the "sprintf" function to convert a number into a string with a specific format. Then display the string on the table.
For example:
data(:,1)=num2cell((1:10)');
rng(1);
% Specify the format using 'sprintf' function
data(:,2)=arrayfun(@(x)sprintf('%.2e',x),rand(10,1)*1e5,'UniformOutput',false);
% Set 'ColumnFormat' of the 4th column to be 'numeric'
% to align the displayed text to the right
app.UITable.ColumnFormat(2)={'numeric'};
% Assign data to the table
app.UITable.Data=data;
The numbers are displayed with scientific notation with 2 digits after the decimal point.
In the "arrayfun" function, the option "UniformOutput" is specified as false to make the output of the "arrayfun" to be a cell array.
Please see the attached file "UseSprintf.mlapp" for the full example.
For more information about the "sprinft" function:
For more information about the "UniformOutput" option in the "arrayfun" function:
3. Use the "cellfun" function:
If you are already using a table with mixed types, you can convert to a mixed "cell" array and convert back to a table after the formatting and converting to strings is applied for numeric values.
>> t = table;
t.A = {'a';'b';'c'};
t.B = [1.03;5;2.400]
t =
3×2 table
A B
_____ ____
{'a'} 1.03
{'b'} 5
{'c'} 2.4
t = cell2table(cellfun(@(c) num2str(c, '%g'), table2cell(t), 'UniformOutput', false))
t =
3×2 table
Var1 Var2
_____ ________
{'a'} {'1.03'}
{'b'} {'5' }
{'c'} {'2.4' }