Search code examples
matlabformatcell-array

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


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]

Solution

  • 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.