Reputation: 1269
I am looking for a functionality i Matlab
to subset and array like the IN
function in SQL or %in%
in R. I.e. I have the following data:
a = 1:3;
b = 2:4;
Then I want to write something like:
(a %in% b)
And it should produce:
ans =
0 1 1
However using %in% clearly doesn't work.
Upvotes: 1
Views: 87
Reputation: 112659
You could also do it with bsxfun
:
result = sum(bsxfun(@eq, a(:).', b(:)), 1);
This has the advantage that it tells you how many elements of b
equal each element of a
. For example,
>> a = [1 2 3];
>> b = [2 3 4 2];
>> result = sum(bsxfun(@eq, a(:).', b(:)),1)
result =
0 2 1
Upvotes: 1
Reputation: 4311
You are probably looking for the function ismember
, which checks which members of one matrix are also member of a second matrix. It returns true/false for each entry in your matrix a
if it can/cannot be found in your matrix b
.
ismember(a, b)
ans =
0 1 1
As a side note: %
is the character, which starts a comment.
Upvotes: 3