Which is the shortest/simplest way to check a subvector in a vector?

For example I would like to check the existence of [1,5] in a larger vector: [2,3,1,5,6,6,1]

 Accepted Answer

Interestingly you can use strfind to locate patterns in numeric vectors as well as in strings. Here are your two examples, the first with a match, the second without:
>> strfind([2,3,1,5,6,6,1], [1,5])
ans =
3
>> strfind([2,3,1,6,5,6,1], [1,5])
ans =
[]
To turn this into a logical value, simply wrap this with ~isempty:
>> ~isempty(strfind([2,3,1,5,6,6,1], [1,5]))
ans =
1

More Answers (0)

Categories

Asked:

on 20 Apr 2015

Edited:

on 21 Apr 2015

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!