查找最频繁连续重复的数字

时间:2019-11-18 17:51:45

标签: arrays matlab

给出以下数组: a = [1 2 2 2 1 3 2 1 4 4 4 5 1]

我想找到一种方法来检查最连续连续重复的数字。在此示例中,由于2和4均连续重复三次,因此输出应为[2 4]。 另一个例子: a = [1 1 2 3 1 1 5]

这应该返回[1 1],因为1的单独实例重复了两次。

这是我的简单代码。我知道有更好的方法可以做到这一点:

function val=longrun(a)

b = a(:)';
b = [b, max(b)+1];
val = [];
sum = 1;
max_occ = 0;
for i = 1:max(size(b))
    q = b(i);
    for j = i:size(b,2)
        if (q == b(j))
            sum = sum + 1;
        else
            if (sum > max_occ)
                max_occ = sum;
                val = [];
                val = [val, q];
            elseif (max_occ == sum)
                val = [val, q];
            end
            sum = 1;
            break;
        end
    end
end
if (size(a,2) == 1)
    val = val'
end
end

2 个答案:

答案 0 :(得分:3)

这是一种矢量化方式:

a = [1 2 2 2 1 3 2 1 4 4 4 5 1]; % input data
t = cumsum([true logical(diff(a))]); % assign a label to each run of equal values
[~, n, z] = mode(t); % maximum run length and corresponding labels
result = a(ismember(t,z{1})); % build result with repeated values
result = result(1:n:end); % remove repetitions

答案 1 :(得分:2)

一种解决方案可能是:

%Dummy data
a = [1 2 2 2 1 3 2 1 4 4 4 5 5]

%Preallocation 
x = ones(1,numel(a));

%Loop 
for ii = 2:numel(a)
    if a(ii-1) == a(ii)
        x(ii) = x(ii-1)+1;
    end
end

%Get the result
a(find(x==max(x)))

带有一个简单的for循环。

此处的目标是,如果向量x中的先前值相同,则增加a的值。

或者您也可以矢量化该过程:

x = a(find(a-circshift(a,1,2)==0)); %compare a with a + a shift of 1 and get only the repeated element.
u = unique(x);                      %get the unique value of x
h = histc(x,u);                     
res = u(h==max(h))                  %get the result