how to find out if a number is even or not

divya r

divya r (view profile)

님이 질문을 제출함. 23 Oct 2012
최근 활동 Jaimin Motavar

Jaimin Motavar (view profile)

님이 댓글을 추가함. 5 Jul 2019
Walter Roberson

Walter Roberson (view profile)

님이 답변을 채택함.
I know in C language, for any number x using x%2 will calculate the remainder when x is divided by 2, which will help decipher whether its even or not.
How can I do this in matlab?

Jaimin Motavar

Jaimin Motavar (view profile)

on 5 Jul 2019
you can do it this in matlab by the very simple way by using implicit function rem(a,b) , where a is devided by b.
for example.
r1=rem(4,2)
r=0;
r2=rem(9,2)
r2=1;

로그인 to comment.

답변 수: 4

Thomas (view profile)

on 23 Oct 2012
Edited by MathWorks Support Team

MathWorks Support Team (view profile)

on 9 Nov 2018

You could perform a modulo division
mod(4,2) % Even number
ans = 0
mod(5,2) % Odd number
ans =1
Answer will be 0 for even number and 1 for odd number
Also try
mod(1:8,2)

댓글 수: 0

로그인 to comment.

Answer by Walter Roberson

Walter Roberson (view profile)

on 23 Oct 2012
Edited by MathWorks Support Team

on 9 Nov 2018

See mod and rem

로그인 to comment.

Answer by Matt J

Matt J (view profile)

on 23 Oct 2012

if bitget(A,1) %odd
else %even
end

Matt J

Matt J (view profile)

on 23 Oct 2012
Note that solutions based on REM and MOD have certain non-robustness to large numbers, though I never quite understood why:
>> mod(bitmax+[1:8],2) %all are even
ans =
0 0 0 0 0 0 0 0
Josh Meyer

Josh Meyer (view profile)

on 10 Oct 2018
In more recent versions of MATLAB, bitmax was replaced by flintmax. This is the largest consecutive floating point number. After flintmax, the value of eps is larger than 1 (slowly increasing in powers of 2), so representable numbers larger than flintmax are no longer consecutive.
So, the reason all of those numbers are even is because flintmax is an even number and the spacing between numbers is eps(flintmax) = 2.

로그인 to comment.