elements of array are odd or even

조회 수: 2 (최근 30일)
pooneh shabdini
pooneh shabdini 2020년 3월 18일
댓글: pooneh shabdini 2020년 3월 21일
clear all
clc
a=round(0+9*rand(10,1));
for n=a
if mod(n,2)==0
disp(n),disp('is even')
elseif n==0
disp(n),disp('is 0')
else
disp(n),disp('is odd')
end
end
the program must check which of the numbers of array are even or odd?but it doesnt work correctly...

채택된 답변

Sriram Tadavarty
Sriram Tadavarty 2020년 3월 18일
Hi Pooneh,
The following updates will perform what is looked for
clear all
clc
a=round(0+9*rand(10,1));
for n=1:length(a) % For loop from 1 to length(a), then access each element of a with n, display n
if mod(a(n),2)==0
disp(num2str(n) + " is even")
elseif n==0
disp(num2str(n) + " is 0")
else
disp(num2str(n) + " is odd")
end
end
Hope this helps.
Regards,
Sriram
  댓글 수: 2
pooneh shabdini
pooneh shabdini 2020년 3월 18일
Hi:) Thank you...but Do you know why my way doesn't work?
Sriram Tadavarty
Sriram Tadavarty 2020년 3월 18일
I can help you understand your code. In your code, you have placed the loop for n = a, here is a is a vector, which implies n is the complete vector but not the single element of the vector. As this is vector that is passed in to the conditions, there is not case satisfied this, going with the else statement. There by not giving what you expected.
So, the modification is made to loop it across each element in the code.
Hope this helps. Regards, Sriram

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

pooneh shabdini
pooneh shabdini 2020년 3월 18일
Thanks again But I've read we can use a vector in this way in for loop....
  댓글 수: 2
Sriram Tadavarty
Sriram Tadavarty 2020년 3월 18일
Yes, you could use. It depends on the purpose of what you intended to do.
pooneh shabdini
pooneh shabdini 2020년 3월 21일
Thank you?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Scope Variables and Generate Names에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by