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

235 次查看(过去 30 天)
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?

采纳的回答

MathWorks Support Team
编辑:MathWorks Support Team 2019-10-30
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 个评论
Sindar
Sindar 2020-8-15
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

尚未输入任何标签。

产品


版本

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by