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 日
編集済み: 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.
Sara Boznik
Sara Boznik 2020 年 8 月 15 日
Is maybe %.nf solution there, where n is random number (%.2f)?

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

タグが未入力です。

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by