0

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]
Eitan T
  • 32,660
  • 14
  • 72
  • 109
Oren
  • 4,711
  • 4
  • 37
  • 63
  • 1
    `format short` displays 4 digits after the decimal place. Too few? – chappjc Dec 04 '13 at 08:52
  • for "printing" use `fprintf` or `sprintf` - for "displaying" it's a bit more complicated. Though I suppose you could override `disp` with your code (containing fprintf I suppose) – bdecaf Dec 04 '13 at 09:03
  • @chappjc the cell array also has strings in it.. – Oren Dec 04 '13 at 09:13

3 Answers3

3

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.

Eitan T
  • 32,660
  • 14
  • 72
  • 109
0

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]
Shai
  • 111,146
  • 38
  • 238
  • 371
0

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))))
idnavid
  • 1,795
  • 17
  • 20