Reputation: 563
How to know if a vector V
belongs to a set S
?
V=[3 7 5]
S={[1 3],[4 9 7 22 4 5],[2 66 4],[8 66 44 12 5 71],[100 45 88 7 1 5 9 73]}
Upvotes: 0
Views: 160
Reputation: 221574
Problem case #1: Assuming you want to find if for each cell in S
, there is at least one element that is also present in V
, you can use this arrayfun
based approach -
out = arrayfun(@(n) any(ismember(S{n},V)),1:numel(S))
For the given inputs, you would get -
>> out
out =
1 1 0 1 1
Or cellfun
based approach (though I would bet my money on arrayfun
based approach for better performance) -
out = cellfun(@(x) any(ismember(x,V)),S)
Problem case #2: If you are looking for exact match between V
and each cell of S
, you can again use arrayfun
-
out = arrayfun(@(n) isequal(V,S{n}),1:numel(S))
Upvotes: 2
Reputation: 4336
You can use cellfun
,
A = cellfun( @(x) isequal(x,V), S );
or
A = cellfun(@isequal,S,repmat({V},size(S)));
will give,
A =
0 0 0 0 0
and sum(A) > 0
will give final results.
Upvotes: 3
Reputation: 8941
You need to go over each vector in the set and check if it's the same as the vector V
:
for i=1:length(S)
if (isequal(S{i},V))
% V is in S
end;
end;
Take notice that you address S
with curly brackets {}
to get the value of the cell and not the cell itself.
Upvotes: 1