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

39 views (last 30 days)
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.

Answers (2)

Paras Gupta
Paras Gupta on 6 Jul 2022
Edited: Paras Gupta on 6 Jul 2022
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 on 6 Jul 2022
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

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!