How do I locate the most repeated elements in an array/vector?

8 次查看(过去 30 天)
For example, we have an array
a = [1 1 1 0 1 1 0 2 2 2]
Given an input of this array, how can I find the number(s) in the array that is/are repeated consecutively most often? i.e. return:
[1 2]
New to matlab and not sure how to do this.

回答(2 个)

Bruno Luong
Bruno Luong 2023-7-18
编辑:Bruno Luong 2023-7-18
a = [1 1 1 0 1 1 0 2 2 2];
i = find([true diff(a)~=0 true]);
n = diff(i);
j = find(n == max(n));
b = a(i(j))
b = 1×2
1 2
  1 个评论
Sebastian
Sebastian 2023-7-23
This seems to work really well, and I've taken the time to really understand it as a new user of MATLAB.
However, I'm getting some sort of horzcat error in Cody's test suite. In my own live script I get my expected answer and I don't get any sort of error. Know what might be going on?

请先登录,再进行评论。


Matt J
Matt J 2023-7-18
编辑:Matt J 2023-7-18

类别

Help CenterFile Exchange 中查找有关 Data Distribution Plots 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by