Search for an array in a matrix to store indices of the matrix where its located.

1 view (last 30 days)
Lets say, I have an array. a= [] of nx1 entries. where n is the no. of entries. I have another matrix, B = (m,m) where m is the no. of entries in the matrix.
I want to apply to get only the row indices of the matrix B, where the entries match. This check should be done column-wise in B. Simple eg. a = [ 100 200 300 400 500] B= [7 100; 8 200; 9 300;10 400;11 500;12 6;] This should give an output [1,2,3,4,5] since the indices in B of the second column match.
I tried ismember, find, interesect without much success.
Thanks for the help, in advance !!
  2 Comments
Guillaume
Guillaume on 21 Dec 2017
Edited: Guillaume on 21 Dec 2017
What should the output be for:
a = [ 100 200 300 400 500]
B = [ 7 100 100
200 200 400
100 300 5
100 400 7
6 7 8]
It could either be
[1 2 3 4]
[1 1 2 2 2 3 3 4 4]
[2 3 4 1 2 3 4 1 2]
Guillaume
Guillaume on 21 Dec 2017
Chaitanya Sanghavi's comment moved here:
Clarifying the question a bit more :
1. All the entries of a = [100 200 300 400 500] will be in the same column as B. 2. In case this is array is present in different columns. chose the smallest row indices of B.

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 21 Dec 2017
I'm not entirely sure what it is you're asking. From your example, it looks like you want to know which rows of B have an element in a, so it wouldn't be indices as per your title. Also what if a row of B has more than one column present in a, should that row be present several time in the output?
With your example inputs, the following give the answer you've shown:
a = [ 100 200 300 400 500]
B = [7 100; 8 200; 9 300;10 400;11 500;12 6;]
[rows, ~] = find(ismember(B, a)) %you have to request two outputs from find to get the rows
  1 Comment
Guillaume
Guillaume on 21 Dec 2017
You've accepted my answer but I'm not sure it's what you want. Particularly, with regards to your clarification, it does not check if all the entries of a are present, and if an entry is present in multiple rows/columns it will return that location multiple time.
I'm still not 100% what it is you exactly want.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!