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?
When you use arithmetic operators with strings, Matlab casts the strings as doubles, which converts a string to ascii values:
Thus, subtraction will work just fine, though addition will give weird results
Converting an array of strings to double results in an array of doubles, therefore the “matrix dimensions must agree”:
Thus, while subtracting
'0'is thus a cool shortcut, I suggest you use STR2DOUBLE instead to avoid confusion.