How do I find the even and odd elements in a vector?

61 ビュー (過去 30 日間)
Paul
Paul 2013 年 9 月 24 日
回答済み: Ashok Kumar 2022 年 6 月 28 日
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 件のコメント
Mohamad karimi
Mohamad karimi 2017 年 10 月 5 日
find(mod(myvec,2)==0)
Jan
Jan 2017 年 10 月 5 日
Usually you can omit the find() and use the faster linear indexing.

サインインしてコメントする。

採用された回答

Youssef  Khmou
Youssef Khmou 2013 年 9 月 24 日
hi Paul,
thats good as you created random 50,100, that first step is important,
odd and even are related to Modulus, even modulus 2 is zero :
T=round(100*rand(20,1));
evens=T(mod(T,2)==0);
odds=T(mod(T,2)~=0);
  4 件のコメント
Priyanka Marudhavanan
Priyanka Marudhavanan 2021 年 6 月 11 日
how to display the cell labels in matlab
Image Analyst
Image Analyst 2021 年 6 月 12 日
@Priyanka Marudhavanan, you forgot to give an example of exactly what you want, like do you want to use fprintf() to run along the array printing to the command window. Or do you want to construct a cell array with the words "even" and "odd" in it? Please clarify. Show us what you want.

サインインしてコメントする。

その他の回答 (4 件)

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 9 月 24 日
編集済み: Azzi Abdelmalek 2013 年 9 月 24 日
Edit
a=randi([50 100],1,20)
evens=a(mod(a,2)==0)
odds=a(mod(a,2)==1)

Jan
Jan 2013 年 9 月 24 日
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
Korede Akinpelumi 2017 年 5 月 16 日
編集済み: Korede Akinpelumi 2017 年 5 月 16 日
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
Ashok Kumar 2022 年 6 月 28 日
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

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

タグ

タグが未入力です。

Community Treasure Hunt

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

Start Hunting!

Translated by