How do I write a code that keeps all the even numbers in a vector and deletes all the odd numbers?

2 views (last 30 days)
I'm wrote a function in which the input is a single number (n), and every number before that all the way down to 1 is multiplied together. (a factorial) How do I change this so that it only multiplies the even numbers between 1 and n?
Code so far:
product = 1;
arrayIndex = [1:1:n];
for i =1:length(arrayIndex)
product = product*arrayIndex(i);
end
disp(product);
Really all I want to know is how to check every number in a vector if it is even.

Accepted Answer

Nicolas Schmit
Nicolas Schmit on 16 Oct 2017
This is how you test if an integer is even.
isEven = @(x) mod(x, 2) == 0
isEven(1)
isEven(2)

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!