Reputation: 1410
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 ];
Upvotes: 12
Views: 18946
Reputation: 11168
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
Upvotes: 13
Reputation: 1647
a = [1 1 1; 2 2 2; 3 3 3];
b = a(1:2,;);
[temp locb] = ismember(a,b,'rows');
b(locb(locb~=0),:)
ans =
1 1 1
2 2 2
Upvotes: 1
Reputation: 6569
You can use ismember
and do it in a single line:
>> ismember(Q,r,'rows')'
ans =
1 0 0 1 1 0
Upvotes: 21
Reputation: 3187
Easier way with repmat
:
a = [1 2 3; 4 5 6; 7 8 9];
t = [4 5 6];
[x,y] = size(a);
r = all(a==repmat(t,y,1), 2)'
Upvotes: 0