【问题标题】:Identify and flag consecutive duplicates MATLAB识别和标记连续重复 MATLAB
【发布时间】:2016-06-12 13:41:28
【问题描述】:

我有一个数字 1 到 8 的列向量。在正常情况下,每个数字有 4 个连续值,从 1 到 8 即: Perfect_sample=[1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 5 5 5 6 6 6 6 7 7 7 7 8 8 8 8]';

模式从 8 之后的一个重新开始。

但是,有时会出现缺失值,并且向量看起来不像上面的那样,而是像这样:

Imperefect_sample=[1 1 2 2 2 3 3 3 3 4 5 5 5 5 6 7 7 7 7 8 8]';

我的目标是用 NaN 替换每组连续相同数字的前两个值:

Perfect_sample_result=[NaN NaN 1 1 NaN NaN 2 2 NaN NaN 3 3 NaN NaN 4 4 NaN NaN 5 5 NaN NaN 6 6 NaN NaN 7 7 NaN NaN 8 8]'

如果只有两个或更少的连续相同数字,则应将这些数字替换为 NaN。

 Imperfect_sample_result=[NaN NaN NaN NaN NaN NaN 2 2 NaN NaN 3 3 NaN NaN NaN NaN NaN NaN 5 5 NaN NaN NaN NaN NaN NaN 7 7 NaN NaN NaN NaN]'

我怎样才能做到这一点?

【问题讨论】:

  • 您能否提供一个具有“两个或更少”连续数字的示例,因为您发布为Imperefect_sample 的数字与结果完全不对应。除非它......?目前还不清楚。
  • @Suever Imperfect 样本确实有两个或更少的连续相同数字,分别是 1、4、6 和 8。我添加了 Imperfect_sample_result。
  • @Buzz 为什么在 2 之前有 5 个 nan?
  • 你是否总是保证每个数字至少出现 1 次
  • @suever 您应该添加一个文本文件或带有您将要使用的数据示例的内容,这会有所帮助

标签: matlab vector indexing identify


【解决方案1】:

根据我的理解,这将起作用。请记住,它不考虑任何大于 4 的事件,因为您没有提到这是可能的。这是基于我从您的原始帖子中了解到的。

clc
clear
Imp=[1 1 2 2 2 3 3 3 3 4 5 5 5 5 6 7 7 7 7 8 8];
perf = Imp;
pos = 1; % position of your cursor
while(pos<max(size(perf))-2) % -2 to avoid going out of range
next = true; %check if it should go further
count = 0; % will store number of consecutive times the iith number appears

    while(next == true) %checks if the next digit in the sequence is the same
        if(perf(pos) == perf(pos+count))
            count = count+1;
        else
            next = false;
        end

    end


 if (count == 1)
     perf(pos) = NaN;
 elseif( count == 2)
     perf(pos:pos+1) = NaN;
 elseif(count == 3)
      perf(pos:pos+2)= NaN;
 elseif(count == 4)
      perf(pos:pos+1)= NaN;
  end

 pos = min(pos+ count,max(size(perf))); % passes the counter to the next value
end

【讨论】:

    猜你喜欢
    • 2022-01-16
    • 2015-09-26
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 2020-06-22
    • 2011-08-23
    • 2020-04-22
    • 2021-09-07
    相关资源
    最近更新 更多