Explanation of num2str(x) - '0'

24 ビュー (過去 30 日間)
Marvin Ott
Marvin Ott 2018 年 5 月 7 日
コメント済み: Rik 2020 年 12 月 15 日
Hi, for my homework I had to split a binary number into it's individual parts. After some tying and research I found out that I can use:
num2str(x) -'0'
I now know that it works but I don't know how it works. Can someone explain it to me?
Thanks in advance.
Marvin

採用された回答

Ameer Hamza
Ameer Hamza 2018 年 5 月 7 日
It works because num2str convert the number into a char array. For example
x = 10001100;
y = num2str(x)
ans =
'10001100'
In computer memory, each character is stored on the basis of its ASCII value. From ASCII table character '1' = 49 (decimal) and '0' = 48 (decimal). Therefore in computer memory y is saved as
y = [49 48 48 48 49 49 48 48]
now when you subtracted '0' = 48 decimal, what you are doing is
[49 48 48 48 49 49 48 48] - 48
which gives you
[1 0 0 0 1 1 0 0]
  2 件のコメント
Abhinandh V
Abhinandh V 2020 年 12 月 15 日
nice
Rik
Rik 2020 年 12 月 15 日
Actually chars are Unicode codepoints encoded with UTF-16 in Matlab (doclink). The difference starts to be relevant beyond 127, and starts to matter a lot beyond 0xFFFF (i.e. beyond the basic multilingual plane, which contains e.g. most emoji).

サインインしてコメントする。

その他の回答 (2 件)

Star Strider
Star Strider 2018 年 5 月 7 日
Character arrays exist as ASCII or other numeric encodings, so that each letter or other character is assigned a numeric value. In MATLAB, they are then handled as any other numeric array.
So:
zerochar = double('0')
chars = '12345'
numarray1 = double(chars)
numarray2 = numarray1 - zerochar
expands to:
zerochar =
48
chars =
'12345'
numarray1 =
49 50 51 52 53
numarray2 =
1 2 3 4 5

David Fletcher
David Fletcher 2018 年 5 月 7 日
編集済み: David Fletcher 2018 年 5 月 7 日
num2str(x) - this converts the number to a string
Once converted subtracting '0' subtracts the character code for 0 from all entries. Therefore all zero characters become the actual value of 0, and all one characters become the actual value of 1 (since the ASCII code for '1' is one greater than the ASCII code for '0'). Subtracting 48 (the ascii code for '0' achieves the same thing).
>> '0' - 48
ans =
0
>> '1' -48
ans =
1
  1 件のコメント
Stephen23
Stephen23 2018 年 5 月 7 日
"num2str(x) - this converts the number to a string"
The output is (for historic reasons) not a string, but is actually a character array.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeString についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by