for loops and odd numbers

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.

 Accepted Answer

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 Comments

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
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
Thank you! I was missing the p = p*x

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Asked:

on 27 Oct 2021

Commented:

on 27 Oct 2021

Community Treasure Hunt

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

Start Hunting!