Can we put all of these str2num in one function?

3 Ansichten (letzte 30 Tage)
Minhao Wang
Minhao Wang am 24 Sep. 2020
Kommentiert: Walter Roberson am 24 Sep. 2020
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()?

Akzeptierte Antwort

madhan ravi
madhan ravi am 24 Sep. 2020
Usually str2num() is not recommended.
Simply use:
sum(C1 - '0')
  3 Kommentare
Minhao Wang
Minhao Wang am 24 Sep. 2020
That helps a lot ! Thank you !

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

David Hill
David Hill am 24 Sep. 2020
sum(C1-'0');
  4 Kommentare
Minhao Wang
Minhao Wang am 24 Sep. 2020
Make sense ! Thank you so much !
Walter Roberson
Walter Roberson am 24 Sep. 2020
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' .

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Data Type Conversion finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by