Finding number(s) that is(are) repeated consecutively most often
조회 수: 19 (최근 30일)
이전 댓글 표시
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
답변 (2개)
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
% 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
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
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Particle & Nuclear Physics에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!