Repeated sequence of numbers in a vector
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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
0 Kommentare
Antworten (1)
Mathieu NOE
am 6 Jan. 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
1 Kommentar
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!