MATLAB: How to display a table with specific number of decimal places in MATLAB Command Window

MATLAB

I have created a table of numeric data. How can I display this table with specific number of decimal places in the MATLAB Command Window?
For example, I created a table:
>> T = table([1.1; 2],[3.45; 1.2], 'VariableNames', {'a', 'b'}, 'RowNames', {'c', 'd'});
and displayed the table in the Command Window:
>> T
T =
2×2 table
a b
___ ____
c 1.1 3.45
d 2 1.2
But I would like to display the table with specific decimal places, say 2 decimals, in the Command Window so that the table looks like:
>> T
T =
2×2 table
a b
____ ____
c 1.10 3.45
d 2.00 1.20
Is there a way of achieving this?

Best Answer

Yes, there is a way of achieving this in MATLAB. The idea is to convert the numeric data to the string format using the "num2str" function and specify the desired decimal places through the "num2str" function. Here is a code that does this:
T = table([1.1; 2],[3.45; 1.2], 'VariableNames', {'a', 'b'}, 'RowNames', {'c', 'd'});
% set desired precision in terms of the number of decimal places
n_decimal = 2;
% create a new table
new_T = varfun(@(x) num2str(x, ['%' sprintf('.%df', n_decimal)]), T);
% preserve the variable names and the row names in the original table
new_T.Properties.VariableNames = T.Properties.VariableNames;
new_T.Properties.RowNames = T.Properties.RowNames;
% display the original table
fprintf('Original table:\n')
T
% display the new table, which has the desired decimal places
fprintf('New table with %d decimal places:\n', n_decimal);
new_T
----------
You can also convert the numbers to string and format them with the "sprintf" command _before _adding them to the table:
%create data and convert numbers to strings
data = [1.1 3.45; 2 1.2];
data_str = string(data);
%round to 2 decimal places
for i = 1:numel(data_str)
data_str(i) = sprintf('%.2f',data_str(i));
end
%add formatted strings to table
t = array2table(data_str,'VariableNames',{'a','b'},'RowNames',{'c','d'})