Finding if a vector is a subset
19 views (last 30 days)
Show older comments
Harel Harel Shattenstein on 10 Apr 2018
Commented: Roger Stafford on 10 Apr 2018
I am trying to build a function that for
a=[1 2] b=[1 3 2 9 5]
will return false
a=[1 2] b=[1 2 2 9 5]
What I manage to do is
function[yn] = subset1(v1,v2)
if length(find(v))==length(find(v1)) && find(v)==find(v1)
if length(find(v))==length(find(v2)) && find(v)==find(v2)
but it does not work in the first case
The following should be faster:
m = size(a,2);
n = size(b,2);
for k = 1:n-m+1
s = all(a==b(k:k+m-1));
if s, break, end
Logical s will be true if any m-length section of b is equal to the a vector.
More Answers (1)
Rik on 10 Apr 2018
strfind should be an option, especially if you only have positive integer scalars, which you can just cast to char. Otherwise, the solution below might also be an option. It might not scale really well to huge vectors due to that convolution, but that is done on a binary matrix, so that should be as fast as it can be.
Another note: this uses implicit expansion, so if you don't have R2016b or newer, you'll have to use bsxfun.
a=[1 2];b1=[1 3 2 9 5];b2=[1 2 2 9 5];
%requires implicit expansion (use bsxfun on R2016a and earlier)
Oh yes: the one restriction here is that strfind() will only work with row vectors, not with column vectors.
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!