Fast "ismember" routine for sorted arrays
Updated 25 Jan 2015

View License

I found that "ismember" is annoyingly slow. I've avoided using it as much as I could, but there are some instances where is it unfortunately necessary. When possible, I try to use "ismembc" or "builtin("_ismemberoneoutput",A,B)" as much as possible (I highly recommend others do the same!), but these are less than optimal as well.
Recently, I found myself in the position of needing to use ismember with two sorted arrays as inputs. After profiling the code, I found that this little function was unforgivably slow. There is no reason there should be so much overhead for two arrays which are pre-sorted.

Anyway, I spent an afternoon writing this silly function. It takes two sorted arrays and returns one array (the same size as the first input).

Example :
>>ismember_mex( [1 3 5], [1 2 3 4 6 7 8] )
ans =


It is quite a bit faster than the normal ismember (or its substitutes) .... (the following was ran in a fresh matlab to avoid that pesky p-code auto-optimizing junk)

>> n = 50000000;
A = sort(ceil(n*rand(n,1)));
B = 1:n;


Elapsed time is 1.042281 seconds.
Elapsed time is 8.390757 seconds.
Elapsed time is 8.598730 seconds.
Elapsed time is 8.298966 seconds.

Finally, I would like to apologize for my code. I like to minimize the number of keypresses, hence things are often jammed together....enjoy.

Cite As

Christopher Harris (2024). ismember_mex.c (, MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2013a
Compatible with any release
Platform Compatibility
Windows macOS Linux
Find more on Operators and Elementary Operations in Help Center and MATLAB Answers
Tags Add Tags

Community Treasure Hunt

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

Start Hunting!
Version Published Release Notes