how to identify each digit of a number?

16 Ansichten (letzte 30 Tage)
Lucas Santos
Lucas Santos am 19 Feb. 2016
Bearbeitet: Stephen23 am 26 Mär. 2021
Is there some way to identify each digit of a number? example: number 1001, digit one=1, digit two=0,digit three=0, digit four=1. i appreciate the help thanks
  3 Kommentare
James Tursa
James Tursa am 19 Feb. 2016
Are you interested in only integers (relatively simple solutions exist), or fractional numbers (non-trivial)?
Lucas Santos
Lucas Santos am 20 Feb. 2016
Bearbeitet: Lucas Santos am 20 Feb. 2016
I'm trying to solve the problem 4 project euler, I did not know the function num2str(x). This is going to increase in my reasoning. Thanks a lot guys, all comments helped me!

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Image Analyst
Image Analyst am 19 Feb. 2016
Try this trick:
number = 1001
digits = num2str(number) - '0'
  4 Kommentare
Stephen23
Stephen23 am 26 Mär. 2021
Bearbeitet: Stephen23 am 26 Mär. 2021
"what does the -'0' do?"
Subtracts the character code for the character '0' (which happens to be 48) from the preceding array.
"is this something you would only use for num2str?"
No, as the Image Analysts comment demonstrates. Just as with numeric arrays, you can subtract character codes (in the form of character arrays) from character arrays, numeric arrays, or logical arrays.
Image Analyst
Image Analyst am 26 Mär. 2021
It subtracts the ASCII value of the character '0' from the ASCII values in the string.
So instead of '1001' being [49, 48, 48, 49], which is a numerical array of the ASCII values, it makes it [1, 0, 0, 1].

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by