This is what is described in one of the examples for ismember:
Define two vectors with values in common.
A = [5 3 4 2]; B = [2 4 4
You can swap the input arguments to ismember
:
[tf, ia] = ismember(B, A)
For your example, you should get:
tf =
1 1 1 1 0 0
ia =
4 3 3 3 0 0
This allows you to find, say, the indices of all the elements of B
that equal A(3)
simply by doing:
find(ia == 3)
Here's a nifty solution for the general case:
[tf, ia] = ismember(B, A);
idx = 1:numel(B);
ib = accumarray(nonzeros(ia), idx(tf), [], @(x){x});
Note that the output is a cell array. For your example, you should get:
ib =
[]
[]
[2 3 4]
[ 1]
which means that there are no elements in B
matching A(1)
and A(2)
, A(3)
matches elements B(2)
, B(3)
and B(4)
, and A(4)
equals B(1)
.