44

I have an m by n matrix in MATLAB, say M. I have an n-element row vector, i.e. a one by n column matrix, say X.

I know X is a row somewhere in M. How can I find the index in M?

Green Falcon
  • 818
  • 3
  • 17
  • 48
shuhalo
  • 5,732
  • 12
  • 43
  • 60

4 Answers4

66

EDIT:

gnovice's suggestion is even simpler than mine:

[~,indx]=ismember(X,M,'rows')

indx =

     3

FIRST SOLUTION:

You can easily do it using find and ismember. Here's an example:

M=magic(4);        %#your matrix

M =

    16     2     3    13
     5    11    10     8
     9     7     6    12
     4    14    15     1

X=[9 7 6 12];      %#your row vector

find(ismember(M,X),1)

ans =

     3
Community
  • 1
  • 1
abcd
  • 41,765
  • 7
  • 81
  • 98
8

Before I learned of ismember, I used to do:

index = find(all(bsxfun(@eq, M, X), 2));

But using ismember(X, M, 'rows') is definitely preferable.

buzjwa
  • 2,632
  • 2
  • 24
  • 37
  • 3
    This is a nice solution since it returns ALL rows of the matrix in which X occurs (unlike the marked answer). – Erik M Apr 01 '15 at 01:11
  • 1
    This solution is far faster than the accepted one (about 20 times on a big scale - tested), and it returns all rows, not just the largest index. – Max Aug 08 '16 at 11:18
  • Interesting. I think I checked for a performance difference before adding this answer and didn't see any, but maybe I didn't use large enough arrays. – buzjwa Aug 08 '16 at 13:18
3

Another solution that returns a row index for each occurrence of X is

find(sum(abs(M-ones(rows(M),1)*X),2)==0)

Also, this solution can be easily adapted to find rows that are within threshold of X as follows (if numerical noise is an issue)

tolerance = 1e-16; %setting the desired tolerance
find(sum(abs(M-ones(rows(M),1)*X),2)<tolerance)
1

This is a non-loop version. It is only suitable, if M (your matrix) is not very large, ie. n and m are small. X is your row:

function ind = findRow(M,X)
    tmp = M - repmat(X,size(M,1),1); 
    ind = find(tmp,1); 
end     

If M is too large, it might be faster, to iterate the rows of M and compare every row with your vector.

@Edit: renamed variables to match the names used in the question.

user492238
  • 4,094
  • 1
  • 20
  • 26