Repeated sequence of numbers in a vector

2 visualizzazioni (ultimi 30 giorni)
Tamir Eisenstein
Tamir Eisenstein il 6 Gen 2022
Commentato: Mathieu NOE il 2 Feb 2022
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

Risposte (1)

Mathieu NOE
Mathieu NOE il 6 Gen 2022
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

Categorie

Scopri di più su Just for fun in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by