问题
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