Extract numbers from an integer

4 vues (au cours des 30 derniers jours)
Jennifer Pettersson
Jennifer Pettersson le 12 Nov 2017
Modifié(e) : Stephen23 le 16 Nov 2017
I want to write code that allows the user to enter a number, for example 123411 and that matlab answers with how many ones the input contains, in this case 3. Can't seem to figure this out!

Réponses (4)

Jan
Jan le 12 Nov 2017
This sounds like a homework question. The solution is not hard and it should be possible to solve. Unfortunately you did not post, what you have tried so far and did not ask a specific question. So how can we help you beside posting the working solution?
s = input('Type in the number: ', 's');
n1 = sum(s == '1')
And now? Can you submit this as your solution? Does it help you to learn Matlab if I post a solution?
Read the docs for nnz for a slightly different solution. And for the next time, please post you code (even if it is not working) and ask specific questions.
  2 commentaires
Jennifer Pettersson
Jennifer Pettersson le 12 Nov 2017
Well, you're right.. I've tried for several hours with both ismember and find but neither did work, or even be near the solution.
Jan
Jan le 13 Nov 2017
Modifié(e) : Jan le 13 Nov 2017
This is fine also:
sum(ismember(s, '1'))
length(find(s == '1'))
length(strfind(s, '1'))
If the number is provided numerically, use sprintf('%g') to convert it to a CHAR vector.

Connectez-vous pour commenter.


KL
KL le 12 Nov 2017
N = 123411;
noOfOnes = nnz((dec2base(N,10) - '0')==1);
  1 commentaire
Jennifer Pettersson
Jennifer Pettersson le 12 Nov 2017
Wow! Thanks alot!

Connectez-vous pour commenter.


Jennifer Pettersson
Jennifer Pettersson le 16 Nov 2017
Is there any possibility to solve this with integers only? For example with mod instead? Can't seem to figure this out!

Stephen23
Stephen23 le 16 Nov 2017
Modifié(e) : Stephen23 le 16 Nov 2017
If you do not want to convert to string and can only perform numeric operations, then you can use mod and division in a loop:
N = 123411;
C = 0;
while N>0
C = C+(1==mod(N,10));
N = floor(N/10);
end
giving:
>> C
C = 3

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by