Why does subtracting '0' from an array of char appear to convert it to a numerical double.
6 ビュー (過去 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
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
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')
double('0')
double('0123456789')-double('0')
Thus, subtracting 48 from the UTF-16 encoded Unicode value will give you the equivalent numbers.
5 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Data Type Conversion についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!