Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding matching rows in matrix

Tags:

matlab

Suppose I have an (m x n) matrix Q, and a row vector r, e.g.

Q = [ 1 2 3 ; 4 2 3 ; 5 6 7 ; 1 2 3 ; 1 2 3 ; 1 2 5 ];

r = [ 1 2 3 ];

What is the easiest way to obtain a logical vector (of length m) that indicates which of the rows in Q are identical (for all elements) to the specified row r?

In the sample case above, that should be

[ 1 0 0 1 1 0 ];
like image 976
reddish Avatar asked May 09 '12 10:05

reddish


People also ask

How do you select rows in a matrix?

Similar to vectors, you can use the square brackets [ ] to select one or multiple elements from a matrix. Whereas vectors have one dimension, matrices have two dimensions. You should therefore use a comma to separate the rows you want to select from the columns.

How do you connect two matrices?

Concatenating Matrices You can also use square brackets to append existing matrices. This way of creating a matrix is called concatenation. For example, concatenate two row vectors to make an even longer row vector. To arrange A and B as two rows of a matrix, use the semicolon.

How do I find an element in an array in Matlab?

In MATLAB the array indexing starts from 1. To find the index of the element in the array, you can use the find() function. Using the find() function you can find the indices and the element from the array. The find() function returns a vector containing the data.


2 Answers

You can use ismember and do it in a single line:

>> ismember(Q,r,'rows')'

ans =

     1     0     0     1     1     0
like image 153
petrichor Avatar answered Oct 24 '22 22:10

petrichor


all(bsxfun(@eq, r, Q),2)'

bsxfun(@eq, r, Q) compares each row and returns a matrix with same size as Q:

>> bsxfun(@eq, r, Q)

ans =

   1     1     1
   0     1     1
   0     0     0
   1     1     1
   1     1     1
   1     1     0

the all function computes if the result of bsxfun is all true along each row separately. Thus it returns:

>> all(ans,2)'

ans =

   1     0     0     1     1     0

and yeah, there is also a transpose operator ' to match your desired row output

like image 28
Gunther Struyf Avatar answered Oct 24 '22 20:10

Gunther Struyf