2

How can I find the row that have all the values from A into the matrix B and display the index of the rows using Matlab?

A= [2 5 6];

B=[1 2 4 9 10 15 27 30; 
   1 2 3 4 5 6 7 8; 
   1 2 3 5 6 9 22 101; 
   2 4 5 6 14 20 22 23]

Thanks

2
  • Just to clarify: in your example you would get rows 2,3 and 4 as output? Or does the [2 5 6] vector need to be contiguous? Commented Mar 15, 2015 at 13:37
  • 1
    All good now, The answer bellow was what I was looking for. Thanks Commented Mar 18, 2015 at 11:56

1 Answer 1

3

With bsxfun in 3D -

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

With bsxfun again, but keeping it in 2D -

ind = find(sum(reshape(any(bsxfun(@eq,B(:),A(:).'),2),size(B)),2)==numel(A))

With ismember -

ind = find(sum(reshape(ismember(B(:),A(:)),size(B)),2)==numel(A))

With pdist2 from Statistics and Machine Learning Toolbox -

ind = find(sum(reshape(any(pdist2(B(:),A(:))==0,2),size(B)),2)==numel(A))

With knnsearch again from Statistics and Machine Learning Toolbox-

[~,dists] = knnsearch(A(:),B(:))
ind = find(sum(reshape(dists==0,size(B)),2)==numel(A))

Sample run -

A =
     2     5     6
B =
     1     2     4     9    10    15    27    30
     1     2     3     4     5     6     7     8
     1     2     3     5     6     9    22   101
     2     4     5     6    14    20    22    23
ind =
     2
     3
     4
Sign up to request clarification or add additional context in comments.

2 Comments

@Emanuel Consider accepting it, by clicking on the checkmark next to the solution. Read more about it here.
And if I have three or four matrices to search through B and get the index similar? A= [2 5 6]; C=[4 5 6]; D=[8 9 10; 2 9 19]; B=[1 2 4 9 10 15 27 30; 1 2 3 4 5 6 7 8; 1 2 3 5 6 9 22 101; 2 4 5 6 14 20 22 23] How can I do this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.