Can we put all of these str2num in one function?

1 次查看(过去 30 天)
clc;clear
C1 = '222222'
str2num(C1(1)) + str2num(C1(2)) + str2num(C1(3)) + str2num(C1(4))...
+ str2num(C1(5)) + str2num(C1(6))
Are we able to put all of these stru2num in one sum()?

采纳的回答

madhan ravi
madhan ravi 2020-9-24
Usually str2num() is not recommended.
Simply use:
sum(C1 - '0')

更多回答(1 个)

David Hill
David Hill 2020-9-24
  4 个评论
Walter Roberson
Walter Roberson 2020-9-24
Once Upon A Time, there lived an powerful wizard named EBCDIC who ruled supreme and was feared by all. But EBCDIC had one weakness: EBCDIC represented the digits in the order '1' '2' '3' '4' '5' '6' '7' '8' '9' '0' ...
...
But seriously, in nearly all computer character sets from the days of 5 bit characters for teletypes, the characters for the digits have been arranged in sequence, '0' '1' '2' '3' '4' '5' '6' '7' '8' '9' . The exact location where the digits start in the alphabet has varied. The early computer character sets were concerned with telex, which was word oriented (for sending messages such as telegrams) rather than being concerned with computation, so historically the encodings for the digits were not placed at the beginning of the binary sequence -- the encoding for '1' historically was never placed at binary value 1. But the exact location within any alphabet does not matter much: if you know that the digits are stored consecutively starting from '0' then you can convert any one digit to its base-10 equivalent by subtracting the value of the encoding of the character '0' from the character, getting the relative offset from '0' . When the digits encoding the characters are in ascending order, then the relative offset for '2' compared to '0' is 2, and '2' (the binary representation of the character) minus '0' (the binary representation of the character) would be decimal 2.
Modern character encodings are strongly based on the work of ANSI to produce ASCII (which in turn built on earlier work.) In modern encodings, the digits start from binary position 48: '0' is encoded as 48, '1' is encoded as 49, and so on. There are some internal structures in ASCII that make that a useful position to store the digits.
But as I indicated, for the purpose of converting digit characters to decimal, all that is needed is that the digits are consecutive and start from '0' .

请先登录,再进行评论。

类别

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

标签

Community Treasure Hunt

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

Start Hunting!

Translated by