How can I display a table with specific number of decimal places in MATLAB Command Window?
조회 수: 208 (최근 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
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
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 Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!