Dark
Dark

Reputation: 333

List all index using ismember

So say I have two arrays:

    A:14 63 13
      38 44 23
      11 12 13
      38 44 23

    B:38 44 23 

I am trying to use ismember to return the index of every location where B is found in A. All examples I have found online only list the first or last occurrence of a match, I am trying to have a list indices for all values that match, even repeating ones. Thanks

Upvotes: 2

Views: 699

Answers (4)

Divakar
Divakar

Reputation: 221524

You can look into pdist2 if you have A and B as Nx3 sized arrays -

[indA,indB] = ind2sub([size(A,1) size(B,1)],find(pdist2(A,B)==0));

ind = [indA,indB]

Thus, in ind you would have the pairwise indices for the matches with the first column representing the indices for A and the second one for B.

Sample run -

A =
    14    63    13
    38    44    23
    11    12    13
    14    63    13
    38    44    23
B =
    38    44    23
    14    63    13
ind =
     2     1
     5     1
     1     2
     4     2

Upvotes: 3

Santhan Salai
Santhan Salai

Reputation: 3898

This is just an improved version of shai's answer for handling multiple rows of B

idx = find(any(all( bsxfun(@eq, A, permute(B,[3 2 1])), 2 ),3));

Sample Run:

A = [14 63 13;
     38 44 23;
     11 12 13;
     38 44 23];

B = [38 44 23;
     11 12 13];

idx = find(any(all( bsxfun(@eq, A, permute(B,[3 2 1])), 2 ),3));

>> idx

idx =

 2
 3
 4

Upvotes: 2

Dan
Dan

Reputation: 45741

Use ismember with the 'rows' arugment:

ismember(A, B, 'rows')

which results in a logical array [0 1 0 1] which is often better than an array of indices but if you want the indices specifically then just use find:

find(ismember(A,B,'rows'))

to return [2,4]

Note that this method will still work if B has multiple rows e.g. B = [38 44 23; 11 12 13], it will return [0; 1; 1; 1]

Upvotes: 6

Shai
Shai

Reputation: 114786

You can use bsxfun for the comarison:

idx = find( all( bsxfun(@eq, A, B), 2 )); %// only where all line matches

Results with

idx =
 2
 4

Upvotes: 5

Related Questions