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.
Get
the MATLAB code
Published with MATLAB® 7.8



One function that I often have to be careful with, is using HIST to count unique members of an array:
This works fine unless x has only one unique element. There is a good submission on FEX that solves this problem but it would be nice to see a built-in version.
Also, anyone working with large integers (bigger than bitmax) should look at John D’Errico’s marvellous Variable Precision Integer toolbox.
This is very impressive indeed. Urs Schwarz’s contribution appears very genius and I will be looking in to this isodd.
Very interesting post, Loren. Unfortunately, I don’t have an example application.
Just wanted to point out that it appears a bitwise logical AND comparison would be more efficient than a modulus operation. To compute the modulus, you have to do a division which tends to be costly computationally… So I find Urs’ code appealing from that perspective. Not 100% sure about Matlab though. What I have in mind is that, AFAIK, C compilers optimize (x%2) to (x&1) if the two are equivalent on the architecture.