How to display formatted numbers from a cell array with n decimal places

一个人想着一个人 提交于 2019-12-25 01:51:21

问题


I have a cell array that contains both numbers and strings. I want to print the cell array so that I will see only 5 numbers after the decimal point. For example:

c{1, 1} = pi;
c{2, 1} = pi / 2;
c{3, 1} = pi / 4;
c{4, 1} = 2 ^ 0.5;

After using format long this is what I receive:

>> c
c = 
    [3.141592653589793]
    [1.570796326794897]
    [0.785398163397448]
    [1.414213562373095]

But I want that the output will be:

>> c
c = 
    [3.14159]
    [1.57079]
    [0.78539]
    [1.41421]

回答1:


A possible solution is to generate a formatted string, e.g:

sprintf('%.5f\n', c{:})

For your example, the result would be:

ans =
    3.14159
    1.57080
    0.78540
    1.41421

Unlike format, generating your own string allows you to tweak the number of digits displayed after decimal point to any value you desire.

If your cell array contains non-numerical values (such as strings), you can do the following hack:

c_fmt = c;                                              %// Temporary cell array
idx = cellfun(@isnumeric, c(:));                        %// Locate numbers
c_fmt(idx) = cellfun(@(x){sprintf('%.5f', x)}, c(idx)); %// Format as strings

which essentially converts the numbers to formatted strings. Displaying the resulting c_fmt should give you an acceptable output.




回答2:


Go to File -> preferences pick "command window" from the list on the left.
Change the "Text display" from 'long' to 'short'

c = 
[3.1416]
[1.5708]
[0.7854]
[1.4142]



回答3:


Use compose:

disp(cell2mat(compose('%1.4f',cell2mat(c))))

This will give you a char per row. To convert it to an array:

str2num(cell2mat(compose('%1.4f',cell2mat(c))))


来源:https://stackoverflow.com/questions/20370661/how-to-display-formatted-numbers-from-a-cell-array-with-n-decimal-places

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!