finding a numeric pattern in an array

조회 수: 11 (최근 30일)
Saikrishna
Saikrishna 2023년 3월 27일
댓글: Saikrishna 2023년 3월 27일
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.

채택된 답변

Stephen23
Stephen23 2023년 3월 27일
편집: Stephen23 2023년 3월 27일
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]
V = 1×133
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
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]))
P = '□□□□□.*?□□□□□□□□□□'
[X,Y,M] = regexp(char(V),P, 'start','end','match') % start & end indices, matched text.
X = 1×2
6 64
Y = 1×2
35 122
M = 1×2 cell array
{'□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□'} {'□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□□'}
Checking the matched content:
double(M{1})
ans = 1×30
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
double(M{2})
ans = 1×59
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
  댓글 수: 3
Stephen23
Stephen23 2023년 3월 27일
편집: Stephen23 2023년 3월 27일
"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]))
P = '□□□□□.*?□□□□□□□□□□'
I will update my answer with this.
Saikrishna
Saikrishna 2023년 3월 27일
@Stephen23 excellent! Thank you :) that worked for me perfectly

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by