MATLAB: Get the row index of matrix where the first 3 columns are equal in two matrix

indexmatrices comparison

Hi I have the matrix A and the matrix B
A = [1 2 3 6 8 9;3 5 1 7 8 89;23 2 4 5 56 7;11 12 14 15 16 17]
B = [1 2 3;11 12 13]
I need to get the Index where the i row of B are in A. In this case get the vector
Indices = [1 4]
to finally obtain the matrix A only with the common row with B, in this case,
D = [1 2 3 6 8 9;11 12 14 15 16 17]
I wrote the next code, but this it seems to be low efficient (takes to long to find 135 rows of B in 27000 rows of A in my real case). Is there a different aproach to be more efficient?
A2 = A(:,1:3);
[rowB,colB] = size(B)
for i = 1:rowB;
B2 = B(i,:);
D = nlfilter(A2, [1 3], @(x) (isequal(x,B2)))
[rowD,colD] = find(D)
Indices(i) = rowD
end
D = A(Indices,:);
Thanks for your help.

Best Answer

Assuming the match is always in the first three columns (caution, untested):
k = ismember(A(:,1:3),B,'rows');
D = A(k,:);
Related Question