Reputation: 935
I have two matrices:
X =
1 2 3
4 5 6
7 8 9
`Y` =
1 10 11
4 12 13
7 14 15
I know that if I want to find the index of a specific element in X
or Y
, I can use the function find
. For example:
index_3 = find(X==3)
What I want is to find or search in a very automatic way if a column in X
is also present in Y
. In other terms, I want a function which can tell me if a column in X
is equal to a column in Y
. In fact to to try this, one can use the function ismember
which indeed has an optional flag to compare rows:
rowsX = ismember(X, Y, 'rows');
So a simple way to get columns is just by taking the transpose of both matrices:
rowsX = ismember(X.', Y.', 'rows')
rowsX =
1
0
0
But how can I do that in other manner?
Any help will be very appreciated!
Upvotes: 2
Views: 69
Reputation: 112769
You can do that with bsxfun
and permute
:
rowsX = any(all(bsxfun(@eq, X, permute(Y, [1 3 2])), 1), 3);
With
X = [ 1 2 3
4 5 6
7 8 9 ];
Y = [ 1 10 11
4 12 13
7 14 15 ];
this gives
rowsX =
1 0 0
How it works
permute
"turns Y
90 degrees" along a vertical axis, so columns of Y
are kept aligned with columns of X
, but rows of Y
are moved to the third dimension. Testing for equality with bsxfun
and applying all(...,1)
gives a matrix that tells which columns of X
equal which columns of Y
. Then any(...,3)
produces the desired result: true
if a column of X
equals any column of Y
.
Upvotes: 1