首页 > 解决方案 > 计算连续重复的值

问题描述

我有一个数据集,通常每半小时有一个数据(所以每小时有 2 个数据),但是有些数据每小时有 3 个数据,我希望删除第 3 个数据。所以,对于每个小时,我想看看连续重复了多少次。

简化示例:

A= [0 0 1 1 2 2 3 3 4 4 4 5 5 6 6 7 7 8 8 9 9 10 11 12 12 13 13 14 14 15 15 16 16 17 17 18 18 19 19 20 20 21 21 22 22 23 23 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 7 8 8 9 9 10 11 12 12 13 13 14 14 15 15 16 16 17 17 18 18 19 19 20 20 21 21 22 22 23 23 0 0 1 1 2 2 3 3 4 4 4 5 5 6 6 7 7 8 8 9 9 10 11 12 12 13 13 14 14 14 15 15 16 16 17 17 18 18 19 19 20 20 21 21 22 22 23 23 ...]

我想知道粗体 4、7 和 14 的坐标是什么因为它们连续重复三次而不是两次。这是我写的代码,但它只输出 Nan 矩阵,并没有用我正在寻找的坐标填充它。

indexes=year(P20102330.Date)==Year & month(P20102330.Date)==Month; % select correct data from dataset
Feb2330=P20102330(indexes,:);

for i=1:24
    vindhours=find(hour(Feb2330.Date)==i-1);%find coordinates, one hour per step
    svindhours=numel(vindhours); 
    blob=[];
    for j =1:svindhours-1
        result=nan(24,svindhours);%make nan matrix
        if vindhours(j)-vindhours(j+1)==1 %find the coordinates which only differ by one (are consequetive)
            blob=[blob, j] % add those coordinates to a vector
            if numel(blob)>2 % if they are repeated more than 2 times, add them to the result matrix
                result(i,j)=vindhours(j)
            end 
        end
    end
end

标签: matlabfind

解决方案


除非我理解错了,否则不需要循环,只需检查数组的每个元素是否与同一数组的以下两个元素匹配:

A = [0 0 1 1 2 2 3 3 4 4 4 5 5 6 6 7 7 8 8 9 9 10 11 12 12 13 13 14 14 15 15 16 16 17 17 18 18 19 19 20 20 21 21 22 22 23 23 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 7 8 8 9 9 10 11 12 12 13 13 14 14 15 15 16 16 17 17 18 18 19 19 20 20 21 21 22 22 23 23 0 0 1 1 2 2 3 3 4 4 4 5 5 6 6 7 7 8 8 9 9 10 11 12 12 13 13 14 14 14 15 15 16 16 17 17 18 18 19 19 20 20 21 21 22 22 23 23];
n = numel(A);
rep3 = A(1:(n-2))==A(2:(n-1)) & A(1:(n-2))==A(3:n);
hrs = A(rep3)

在输入中,4 重复了两次,因此出现了两次:

hrs =

     4     7     4    14

如果您想要唯一值,请使用该unique功能...


推荐阅读