How can I display a table with specific number of decimal places in MATLAB Command Window?

262 views (last 30 days)
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?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 30 Oct 2019
Edited: MathWorks Support Team on 30 Oct 2019
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'})
  2 Comments
Sindar
Sindar on 15 Aug 2020
Are there plans to implement this more directly in Matlab, similar to the datetime format options? This way works, but seems like potentially a lot of extra computations/memory for a process that Matlab already has to do something like in the background if I change my display format (e.g., format longg). A nice start would be to add format options to head and tail.

Sign in to comment.

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Tags

No tags entered yet.

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!