I am trying to solve the following exercice:
Write a function that fulfill the following task: Return 1 if all elements of an input vector are even and 0 else.
My answer:
function y = iseven(v)
% return the value 1 if all arguments are even, otherwise it return the value 0.
% INPUT v 1xn .. elements of the vector v.
% OUTPUT y 1x1 .. either 1 or 0.
% USAGE iseven(v)
a = rem(v,2);
b = sum(a);
if b==0;y=1;end
if b~=0;y=0;end
Unfortunantly this is not working for the vector -2 -1 0 1 2
Can someone help me to find a solution?

댓글 수: 3

Ankit
Ankit 2019년 10월 9일
편집: Ankit 2019년 10월 9일
Is this what you are looking for?
function y = iseven(v)
% return the value 1 if all arguments are even, otherwise it return the value 0.
% INPUT v 1xn .. elements of the vector v.
% OUTPUT y 1x1 .. either 1 or 0.
% USAGE iseven(v)
res = mod(v,2)==0;
if all(res == 1)
y = 1;
else
y = 0;
end
@Stephen Thanks for pointing out
Stephen23
Stephen23 2019년 10월 9일
@Ankit : your function does not return any output.
The rem function returns a negative result when given a negative input so just summing these will not give what you want. e.g. on the input that fails for you
>> a = rem( v, 2 )
a =
0 -1 0 1 0
You should get used to using the debugger and command line to test these things out. Then you will easily see this for the given input and can work towards improving your solution.
Or you could just pick up a completely different ready made solution from a forum of course rather than learning to evolve your solution into a correct one...

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

답변 (1개)

Daniel M
Daniel M 2019년 10월 9일

0 개 추천

function y = iseven(v)
y = all(~mod(v,2));
end

카테고리

도움말 센터File Exchange에서 Function Creation에 대해 자세히 알아보기

제품

태그

질문:

2019년 10월 9일

답변:

2019년 10월 9일

Community Treasure Hunt

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

Start Hunting!

Translated by