2.44444

2.4 | 9 ratings Rate this file 35 downloads (last 30 days) File Size: 253 Bytes File ID: #2006

isodd

by Richard Medlock

 

18 Jul 2002 (Updated 19 Jul 2002)

No BSD License  

Checks to see if a number is odd or even.

Download Now | Watch this File

File Information
Description

Determines if a number is odd or even by dividing the number by two an seeing if the number is an integer.

MATLAB release MATLAB 6.1 (R12.1)
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Comments and Ratings (12)
22 Jul 2002 anonymous anonymous

This is a lot of code, this should just be one line:

x = mod(number,2)~=0;

This is vectorized, and works for negatives, too. If you want the test to fail for negatives, then use:

x = mod(number,2)>0;

24 Jul 2002 The Author

Well had I known that, I could have used that. But this is an old function, and a fairly simplistic method that works.

However, I have now adpoted the above method as it does allow you to use vetors.

02 Dec 2002 Rasmus Anthin

Myself I use "~~mod(x,2)" all the time nowadays (then "~mod(x,2)" as "iseven()" of course). If you wan't to go fast then I think your way is better. Unfortunately your routine only works for scalars. Instead try:
~~(x/2-floor(x/2))
which is vectorized and FAST (since "floor" is inbuilt. Type "type mod" and you'll see why). This is about 5 times faster than ~~mod(x,2).

17 Jan 2004 Lewis Camill

good...

09 Jun 2005 Camilo Cano

Great and simple. Thanks.

05 Dec 2005 Duane Hanselman

Works only for scalar inputs when it could easily work for an array of any dimension. Problem made much more difficult than needed. Rasmus review provides a simple one-liner.

25 Jan 2006 Mohammed Serhir

to complicated for simple function

20 Sep 2006 John Dough

should there be an "a whole" joke here?

08 Dec 2006 Johan Tolosa

What is Rasmus review's one liner? Can you post it here please?

Thanks.

12 Dec 2006 Matlab Noob

alternatively, one could use

isodd=inline('x-2*floor(x/2)','x');

02 Mar 2008 D St

The function would be more efficient if it avoided calculating the "part" variable, avoided using an "if", and just did its job by "x = (a != whole)"

19 Mar 2008 aanon aanon

even easier, whole thing

rem(number/2)

true if odd, false if even.

Please login to add a comment or rating.
Tag Activity for this File
Tag Applied By Date/Time
parity Richard Medlock 22 Oct 2008 06:46:43
odd Richard Medlock 22 Oct 2008 06:46:43
even Richard Medlock 22 Oct 2008 06:46:43
logic Richard Medlock 22 Oct 2008 06:46:43
mathematics Richard Medlock 22 Oct 2008 06:46:43

Contact us at files@mathworks.com