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

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.

5 Comments

In your example, it is not clear why the 2nd row of B [11 12 13] matches the row of A [11 12 14 15 16 17]. Is this a typo? Or what is the rule for matching?
Sorry. You´re right. The matrix B is:
B = [1 2 3;11 12 14]
Will B always match A in the first three columns? Or could it match in any of the columns?
Will B always match A in the first three columns? Or could it match in any of the columns?
B must match A in the first three columns.

Sign in to comment.

 Accepted Answer

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

More Answers (0)

Categories

Find more on Mathematics in Help Center and File Exchange

Asked:

on 10 Nov 2015

Commented:

on 10 Nov 2015

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!