Finding number(s) that is(are) repeated consecutively most often
18 次查看(过去 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!