How do I find the even and odd elements in a vector?
Show older comments
I'm a student learning MATLAB and am just beginning. I have the following problem to answer:
Generate a vector of 20 random integers, each in the range from 50 to 100. Create a variable "evens" that stores all of the even numbers from the vector, and a variable "odds" that stores the odd numbers.
I created the vector of 20 random integers and named it myvec, but I have tried so many different expressions and cannot seem to find a way to find the even numbers and the odd numbers.
I've tried:
find(myvec==even)
find(myvec==odd)
find(myvec==[50:2:100])
find(myvec=[51:2:99])
None of these work, so can anyone please help?
2 Comments
Mohamad karimi
on 5 Oct 2017
find(mod(myvec,2)==0)
Jan
on 5 Oct 2017
Usually you can omit the find() and use the faster linear indexing.
Accepted Answer
More Answers (4)
Azzi Abdelmalek
on 24 Sep 2013
Edited: Azzi Abdelmalek
on 24 Sep 2013
Edit
a=randi([50 100],1,20)
evens=a(mod(a,2)==0)
odds=a(mod(a,2)==1)
1 Comment
Azzi Abdelmalek
on 24 Sep 2013
Look at Edit
Jan
on 24 Sep 2013
0 votes
Because this is obviously a homework, it would be a good idea to show us, what you have tried so far. "Even" means, that the value can be divided by 2 such that the result has an integer value. While this is exactly what mod(x, 2) does, you can formulate it in many different ways. Perhaps divide by 2, round(), multiply by 2 and compare with the input.
Korede Akinpelumi
on 16 May 2017
Edited: Korede Akinpelumi
on 16 May 2017
0 votes
function [evens,odds]=assignm
A=randi(51,1,20)+49;
B=50:2:100;
C=51:2:99;
evens=intersect(A,B);
odds=intersect(A,C);
end
Ashok Kumar
on 28 Jun 2022
0 votes
Write a code to get one value from user and a. Print the multiplication table for that value in a proper format b. Check whether the given number is odd or even and display it
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!