I am trying to write a script that will find the product of all odd numbers that count up to a user input value. How can I write the code to identify the odd digits? If the user entered 8 I need to be able to single out the values of 1 3 5 7 to the multiply together.

 Réponse acceptée

KSSV
KSSV le 27 Oct 2021
n = 8 ;
x = 1:n ;
idx = mod(x,2)
idx = 1×8
1 0 1 0 1 0 1 0
odd_nus = x(logical(idx))
odd_nus = 1×4
1 3 5 7

4 commentaires

and finally do product
n = 8 ;
x = 1:n ;
idx = mod(x,2) ;
odd_nus = x(logical(idx))
odd_nus = 1×4
1 3 5 7
Product_Value = prod(odd_nus)
Product_Value = 105
Emma Rash
Emma Rash le 27 Oct 2021
This helped a lot thank you so much! Do you happen to know why I cant put it into a for loop? It works perfectly until I add the for statement
n = 8 ;
p = 1 ; % product
for x = 1:n ;
if mod(x,2)
p = p*x ;
end
end
p
p = 105
Emma Rash
Emma Rash le 27 Oct 2021
Thank you! I was missing the p = p*x

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide 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