Find and match multiple values in a matrix with MATLAB's ismember function

I was preparing some results of an image segmentation algorithm for publishing and needed a way to find all pixels that match a variable set of multiple numbers (e.g. find all elements in the array a that has value 1 or 2). Normally, you can use find with a boolean or, as in:

find(a == 1 | a == 2)

This lets you find all the subscripts of a that is equal to 1 or 2. This is fine but gets cumbersome if you had to match a dozen possible numbers or if the numbers you want to match come as a vector or list (e.g. find all elements in a that match [1 2 4 5]). Then you would have to use some kind of for loop with find. I just found out that there is actually an easier way using MATLAB's ismember function.

Make an array to test with:

>> a = [1 2; 4 5; 7 8]

a =

     1     2
     4     5
     7     8

Now, let's look at how the condition parameter in find actually works:

>> (a == 1 | a == 2)

ans =

     1     1
     0     0
     0     0

The parameter that find takes is simply a logical array where elements in a that match either 1 or 2 are 1 and all other elements are 0.

Let's see what ismember does:

>> ismember(a,[1 2])

ans =

     1     1
     0     0
     0     0

This produces the same output, but you can specify the multiple values you want to match using an array. So the following works too:

>> ismember(a,[1 2 4 5])

ans =

     1     1
     1     1
     0     0

Thus, you can do this with find:

>> find(ismember(a,[1 2 4 5]))

ans =

     1
     2
     4
     5

This lists the subscripts for all elements in a that are equal to 1, 2, 4 or 5.

About Peter Yu I am a research and development professional with expertise in the areas of image processing, remote sensing and computer vision. I received BASc and MASc degrees in Systems Design Engineering at the University of Waterloo. My working experience covers industries ranging from district energy to medical imaging to cinematic visual effects. I like to dabble in 3D artwork, I enjoy cycling recreationally and I am interested in sustainable technology. More about me...

Feel free to contact me with any questions about this site at [user]@[host] where [user]=web and [host]=peteryu.ca

Copyright © 1997 - 2021 Peter Yu