finding a numeric pattern in an array
15 views (last 30 days)
Show older comments
Hi all,
I have a big numeric vector and I am trying to find a pattern in the vector.
Example:
my numeric vector = [11 5 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 11 2 31 5 1 2 11 2 31 5 1 2 11 2 31 5 1 2 11 2 31 5 1 2 11 2 31 5 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 11 2 31 5 1 2 11 2 31 5 1 2 11 2]
pattern : [1 2 3 4 5 *any numbers* 1 2 3 4 5 1 2 11 2 31]
I know strfind works well if I know the exact sequence of pattern. But for the above case I am unable to find the solution.
0 Comments
Accepted Answer
Stephen23
on 27 Mar 2023
Edited: Stephen23
on 27 Mar 2023
V = [11,5,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,11,2,31,5,1,2,11,2,31,5,1,2,11,2,31,5,1,2,11,2,31,5,1,2,11,2,31,5,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,11,2,31,5,1,2,11,2,31,5,1,2,11,2]
F = @(v) regexptranslate('escape',char(v));
P = sprintf('%s.*?%s',F([1,2,3,4,5]),F([1,2,3,4,5,1,2,11,2,31]))
[X,Y,M] = regexp(char(V),P, 'start','end','match') % start & end indices, matched text.
Checking the matched content:
double(M{1})
double(M{2})
3 Comments
Stephen23
on 27 Mar 2023
Edited: Stephen23
on 27 Mar 2023
"can't we just take char([1 2 3 4 5 '.*?' 1 2 3 4 5 1 2 11 2 31])?"
That should work the same as my original answer, but ... I realized that we also need to account for special characters that need escaping, so you might also need to use REGEXPTRANSLATE something like this:
F = @(v) regexptranslate('escape',char(v));
P = sprintf('%s.*?%s',F([1,2,3,4,5]),F([1,2,3,4,5,1,2,11,2,31]))
I will update my answer with this.
More Answers (0)
See Also
Categories
Find more on Characters and Strings 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!