Finding islands of zeros in a sequence

后端 未结 6 512
小蘑菇
小蘑菇 2020-11-22 14:05

Imagine you have a very long sequence. What is the most efficient way of finding the intervals where the sequence is all zeros (or more precisely the sequence drops to near-

6条回答
  •  臣服心动
    2020-11-22 14:46

    These are the steps I would take to solve your problem in a vectorized way, starting with a given vector sig:

    • First, threshold the vector to get a vector tsig of zeros and ones (zeroes where the absolute value of the signal drops close enough to zero, ones elsewhere):

      tsig = (abs(sig) >= eps);  %# Using eps as the threshold
      
    • Next, find the starting indices, ending indices, and duration of each string of zeroes using the functions DIFF and FIND:

      dsig = diff([1 tsig 1]);
      startIndex = find(dsig < 0);
      endIndex = find(dsig > 0)-1;
      duration = endIndex-startIndex+1;
      
    • Then, find the strings of zeroes with a duration greater than or equal to some value (such as 3, from your example):

      stringIndex = (duration >= 3);
      startIndex = startIndex(stringIndex);
      endIndex = endIndex(stringIndex);
      
    • Finally, use the method from my answer to the linked question to generate your final set of indices:

      indices = zeros(1,max(endIndex)+1);
      indices(startIndex) = 1;
      indices(endIndex+1) = indices(endIndex+1)-1;
      indices = find(cumsum(indices));
      

提交回复
热议问题