0

I have two matrices and I want to find the indices of rows in Matrix B which have the same row values in Matrix A. Let me give a simple example:

A=[1,2,3; 2,3,4; 3,5,7; 1,2,3; 1,2,3; 5,8,6];
B=[1,2,3; 29,3,4; 3,59,7; 1,29,3; 1,2,3; 5,8,6;1,2,3];

For example, for first row in matrix A, The row1, row5, and row7 in Matrix B are correspondences. I have written below code but it doesn't return back all indices which have the same row value in matrix A and only one of them (row7) is backed !!

A_sorted = sort(A,2,'descend'); % sorting angles
B_sorted = sort(B,2,'descend');   % sorting angles
[~,indx]=ismember(A_sorted,B_sorted,'rows')

the result is

indx_2 =

 7
 0
 0
 7
 7
 6

It means for the first row in matrix A , only one row ( row 7) in Matrix B is available !! But as you can see for first row in matrix A there is three correspondent rows in matrix B (Row 1, row 5 and row 7)

Austin Mullins
  • 7,307
  • 2
  • 33
  • 48
Reza_M
  • 431
  • 2
  • 4
  • 14

2 Answers2

2

I think the best strategy is to apply ismember to unique rows

%make matrix unique
[B_unique,B2,B3]=unique(B_sorted,'rows')
[~,indx]=ismember(A_sorted,B_unique,'rows')
%For each row in B_unique, get the corresponding indices in B_sorted
indx2=arrayfun(@(x)find(B3==x),indx,'uni',0)
Daniel
  • 36,610
  • 3
  • 36
  • 69
1

If you want to compare all pairs of rows between A and B, use

E = squeeze(all(bsxfun(@eq, A, permute(B, [3 2 1])), 2));

or equivalently

E = pdist2(A,B)==0;

In your example, this gives

E =
     1     0     0     0     1     0     1
     0     0     0     0     0     0     0
     0     0     0     0     0     0     0
     1     0     0     0     1     0     1
     1     0     0     0     1     0     1
     0     0     0     0     0     1     0

The value E(ia,ib) tells you if the ia-th row of A equals the ib-th row of B.

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147