Repeated sequence of numbers in a vector

조회 수: 4 (최근 30일)
Tamir Eisenstein
Tamir Eisenstein 2022년 1월 6일
댓글: Mathieu NOE 2022년 2월 2일
Dear MATLAB experts,
I was wondering how can I count the number of times a sepcific sequence of numbers apears in a vector. In adittion, how can I calculate the maximal number of times this sequence apeared in a consecutive order.
For example:
I have a vector M = [1,2,3,4,5,7,2,5,3,6,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,7,4,1,2,3,4,5,1,2,3,4,5,7,2,1,2,3,4,5]
1) Get the number of times the sequence "1,2,3,4,5" appears - in this case 7 [1,2,3,4,5,7,2,5,3,6,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,7,4,1,2,3,4,5,1,2,3,4,5,7,2,1,2,3,4,5]
2) What is the highest number of consecutive repetitions of the full sequence - in this case 3
[1,2,3,4,5,7,2,5,3,6,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,7,4,1,2,3,4,5,1,2,3,4,5,7,2,1,2,3,4,5]
Many thanks!
Tamir

답변 (1개)

Mathieu NOE
Mathieu NOE 2022년 1월 6일
maybe this
M = [1,2,3,4,5,7,2,5,3,6,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,7,4,1,2,3,4,5,1,2,3,4,5,7,2,1,2,3,4,5]
Ms = sprintf('%d',M);
a = [1,2,3,4,5];
as = sprintf('%d',a);
ind = strfind(Ms,as);
qty1 = length(ind); % 7
a = (diff(ind) == length(as)); % here we see 2 consecutive ones (and we must add +1 to have all 3 values)
% a = 0 1 1 0 1 0
% the two consecutives 1 can be identified
% by doing again a diff of a
qty2 = 2 + numel(find(abs(diff(a))<eps)); % 3

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by