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 ];
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.
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.
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.
You can use ismember
and do it in a single line:
>> ismember(Q,r,'rows')'
ans =
1 0 0 1 1 0
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With