Explain the use of "str - '0'" when converting a string to an integer.

matlab, string

Solution

When you use arithmetic operators with strings, Matlab casts the strings as doubles, which converts a string to ascii values:

>> double('1')
ans =
    49

Thus, subtraction will work just fine, though addition will give weird results

>> '1'+'1'
ans =
    98

Converting an array of strings to double results in an array of doubles, therefore the "matrix dimensions must agree":

>> double('10')
ans =
    49    48

Thus, while subtracting `'0'` is thus a cool shortcut, I suggest you use STR2DOUBLE instead to avoid confusion.

Problem

I have noticed that a really cool method to convert a string, say ``` str = '1234' ``` to a vector is to use this trick. ``` vec = str - '0' = [1 2 3 4] ``` My question is why does this method work? Further, something like: ``` vec1 = str -'1' = [0 1 2 3] ``` but ``` vec2 = str - '10' Error using - Matrix dimensions must agree. ``` What is taking place here?

Original source