Search code examples
dynamic-typingtype-systemsmatlab

Matlab: Why is '1' + 1 == 50?


Matlab has weak dynamic typing, which is what causes this weird behaviour. What I do not understand is what exactly happens, as this result really surprises me.

Edit: To clarify, what I'm describing is clearly a result of Matlab storing chars in ASCII-format, which was also mentioned in the comments. I'm more interested in the way Matlab handles its variables, and specifically, how and when it assigns a type/tag to the values.

Thanks.


'1' 

is a 1-by-1 matrix of chars in matlab and

'123' 

is a 1-by-3 matrix of chars.

As expected,

1

returns a 1-by-1 double.


Now if I enter

'1' + 1

I get 50 as a 1-by-1 double, and if I enter

'123' + 1

I get a 1-by-3 double

[ 50 51 52 ]

Furthermore, if I type

'a' + 1

the result is

98

in a 1-by-1 double.

I assume this has to do with how Matlab stores char-variables in ascii form, but how exactly is it handling these? Are the data actually unityped and tagged, or how does it work?

Thanks.


Solution

  • In MATLAB, a string is just a vector of ASCII characters. You can see more on ascii on wikipedia.

    When you mix characters and doubles MATLAB will convert the character to its equivalent ASCII number and return the result. So '1' becomes 49 and 49 + 1 = 50.

    When you write '123' + 1 this becomes [49 50 51] + 1 and MATLAB correctly computes the result as [50 51 52] because a scalar number plus a vector results in the scaar number being added to each element of of the vector.

    Finally, 'a' has the integer value 97 so this all works out.

    Edit:

    Note that you can use the MATLAB command str2double to convert the character to its actual number representation as in the following:

    str2double('1') + 1
    str2double('123') + 1