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.
Discussion
This is pretty interesting one. But I would like to know the other elements around instead of similar elements.
say a = [ 1 2 3] and b = [2 3].
I need the solution such that "1" is not present in b.
Thank you,
Krishna.
This is pretty interesting one. But I would like to know the other elements around instead of similar elements.
say a = [ 1 2 3] and b = [2 3].
I need the solution such that "1" is not present in b.
Thank you,
Krishna.