Why does subtracting '0' from an array of char appear to convert it to a numerical double.

8 次查看(过去 30 天)
X = '11231101' is an array of char
X - '0' seems to convert it to an array of double (I have seen coding doing this)
How is this working and where can I find an explanation of it. It looks very useful, but I want to understand it before I use it for real.
  1 个评论
Stephen23
Stephen23 2023-1-27
编辑:Stephen23 2023-1-27
"How is this working and where can I find an explanation of it."
It simply subtracts the character codes of each character. Unicode character codes are briefly introduced here:
Like everything else on your computer, text is really just long lists of numbers, so there is no reason why they cannot be subtracted, multiplied, added, etc.

请先登录,再进行评论。

采纳的回答

Rik
Rik 2023-1-27
The minus function is not really defined for char, so the operands need to be converted to a datatype that is supported.
Since char is a UTF-16 encoding, subtracting '0' from a char vector will convert the array to double, essentially converting all characters to their Unicode representation. Since those were developed by people to make sense, they just happen to be in increasing order.
double('0123456789')
ans = 1×10
48 49 50 51 52 53 54 55 56 57
double('0')
ans = 48
double('0123456789')-double('0')
ans = 1×10
0 1 2 3 4 5 6 7 8 9
Thus, subtracting 48 from the UTF-16 encoded Unicode value will give you the equivalent numbers.
  5 个评论
Rik
Rik 2023-1-27
It doesn't even hold for 'normal' arabic numerals if you look at superscript (because 123 were introduced at an earlier stage):
low='₀₁₂₃₄₅₆₇₈₉';low_zero=low(1);
sup='⁰¹²³⁴⁵⁶⁷⁸⁹';sup_zero=sup(1);
low-low_zero
ans = 1×10
0 1 2 3 4 5 6 7 8 9
sup-sup_zero
ans = 1×10
0 -8119 -8126 -8125 4 5 6 7 8 9

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

产品


版本

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by