Finding number(s) that is(are) repeated consecutively most often
17 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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.
0 Kommentare
Antworten (2)
Paras Gupta
am 6 Jul. 2022
Bearbeitet: Paras Gupta
am 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
% 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]
% 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)
% 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)
% Find the maximum consecutive occurence
maxCount = max(E)
% There can be multiple consective occurences withcount same as the maximum
idx = find(E == maxCount)
% 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))
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))
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!
0 Kommentare
Matt J
am 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
0 Kommentare
Siehe auch
Kategorien
Mehr zu Creating and Concatenating Matrices 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!