Loren on the Art of MATLAB

Turn ideas into MATLAB


Loren on the Art of MATLAB has been archived and will not be updated.

Evens and Odds

There are so many functions in MATLAB that sometimes users think that if they can't find the function they are thinking of, it's because they don't know the name. Sometimes that's true, and sometimes it's because there's a quick, easy way to get the task done. There are relatively frequent questions on the MATLAB newsgroup regarding how to determine if numbers are even or odd.

The most frequent answers involve people pointing to functions such as rem and mod. However, on these same threads, you will frequently see Urs Schwarz warn about the limitations of those functions for the purpose of determining even/odd-ness. He has made a contribution, isodd on the File Exchange that encapsulates the algorithm he prefers, based on he functions bitmax and bitand The main issues Urs handles that aren't fully handled with solutions based on rem or mod include non-integer inputs and doubles larger than the largest floating point integer.

If you do lots of error checking already, and know that your data is within acceptable bounds, you are probably fine using an approach based on rem or mod. Do you have applications where an enhanced version, such as the one Urs has posted, is important? Let me know here.

Published with MATLAB® 7.8

  • print


To leave a comment, please click here to sign in to your MathWorks Account or create a new one.