Finding number(s) that is(are) repeated consecutively most often

조회 수: 19 (최근 30일)
Edgard El Cham
Edgard El Cham 2019년 11월 18일
답변: Matt J 2022년 7월 6일
Given this array for example:
a = [1 2 2 2 1 3 2 1 4 4 4 5 1]
I want to find a way to check which numbers are repeated consecutively most often. In this example, the output should be [2 4] since both 2 and 4 are repeated three times consecutively.
Another example:
a = [1 1 2 3 1 1 5]
This should return [1 1] because there are separate instances of 1 being repeated twice.

답변 (2개)

Paras Gupta
Paras Gupta 2022년 7월 6일
편집: Paras Gupta 2022년 7월 6일
Hi,
It is my understanding that you intend to find all the numbers for which consective occurence is maximum. The following code illustrates how to achieve the same.
A = [1 2 2 2 1 3 2 1 4 4 4 5 1];
% B is a logical array with true(1) at indices where the difference between adjacent
% elements is not zero
B = diff(A)~=0
B = 1×12 logical array
1 0 0 1 1 1 1 1 0 0 1 1
% Append 1 at the start and end so that the first and last elements of A
% are also considered during the computation
C = [1, B, 1]
C = 1×14
1 1 0 0 1 1 1 1 1 0 0 1 1 1
% D gives us the indices in A where current element is different than the previous element
% (that is no consective occcurence with the previous element)
D = find(C)
D = 1×10
1 2 5 6 7 8 9 12 13 14
% E gives us the count of consecutive occurences for all elements in A. We can verify the sum
% of elements in E is equal to the length of A
E = diff(D)
E = 1×9
1 3 1 1 1 1 3 1 1
% Find the maximum consecutive occurence
maxCount = max(E)
maxCount = 3
% There can be multiple consective occurences withcount same as the maximum
idx = find(E == maxCount)
idx = 1×2
2 7
% D(idx) gives us the indices in A where maximum consective occurences start
% array m gives us the numbers repeated consecutively most often
values = A(D(idx))
values = 1×2
2 4
A compact way to write down the above code, provided for reference.
B = [1 1 2 3 1 1 5];
x = find([1, diff(B)~=0, 1]);
y = diff(x);
maxCount = max(y);
indices = find(y == maxCount);
values = B(x(indices))
values = 1×2
1 1
You can refer to the linked documentations for diff, find, and max functions for a better understanding of how the above code works.
Hope this helps!

Matt J
Matt J 2022년 7월 6일
Using,
>> a = [1 2 2 2 1 3 2 1 4 4 4 5 1];
>> [starts,~,runLengths]=groupLims(a);
>> a(starts(runLengths==max(runLengths)))
ans =
2 4

카테고리

Help CenterFile Exchange에서 Particle & Nuclear Physics에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by