Search code examples
matlabzeronotation

Why does Matlab ( using default short ) show a 0 in vector/matrix output with a scientific notation when it should show a 1?


If we take for example a vector of one line

>>m = linspace(0,100,11)
>>J = exp(m.^0.25)

we get

J =

  Columns 1 through 4

    1.0000    5.9197    8.2875   10.3848

  Columns 5 through 8

   12.3650   14.2841   16.1700   18.0385

  Columns 9 through 11

   19.8996   21.7599   23.6243

We get the right result in the first entry of the output matrix which is e^(0^0.25) = e^0 = 1

But if we take

>> J = exp(m.^2.5)

We get

J =

  1.0e+137 *

  Columns 1 through 4

    0.0000    2.1676       Inf       Inf

  Columns 5 through 8

       Inf       Inf       Inf       Inf

  Columns 9 through 11

       Inf       Inf       Inf

But e^(0^2.5) = e^0 = 1

I did not use matlab for a long time I don't have a good idea how this works, I first thought it could be a round off or a truncation or both, I looked up what the operation was and some documentation of the formats, I found that it does show the right result within the vector using the format longE :

>>format longE

which returns 1.000000000000000e+00

but then I checked the first matrix with the enry 0 ( Default format short) by using

>>J(1)

And it returned 1.

So the value in that entry is correct but it shows 0 , and a factor outside the matrix 1.0e+137 *
I don't get what is happening, why it shows a 0 ?


Solution

  • When displaying a matrix in format long, MATLAB chooses a factor which is suitable for all entries. An example for the purpose of explanation:

    k=10.^[1:10]
    
    k =
    
       1.0e+10 *
    
        0.0000    0.0000    0.0000    0.0000    0.0000    0.0001    0.0010    0.0100    0.1000    1.0000
    

    The first entry is a 10, but because of the factor of 10 000 000 000 it is not displayed. When you instead type in k(1) matlab will choose a format suitable for that number:

    >> k(1)
    
    ans =
    
        10
    

    The standard output is "usually" good where all numbers in a similar magnitude. A workaround is to use mat2str.

    >> mat2str([pi,10.^[1:20]])
    
    ans =
    
        '[3.14159265358979 10 100 1000 10000 100000 1000000 10000000 100000000 1000000000 10000000000 100000000000 1000000000000 10000000000000 100000000000000 1e+15 1e+16 1e+17 1e+18 1e+19 1e+20]'
    

    It displays up to 15 digits which is usually enough, but 17 digits would be required to display a double in full accuracy (further information)