Finding islands of zeros in a sequence

后端 未结 6 473
小蘑菇
小蘑菇 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 15:07

    As gnovice showed, we'll do a threshold test to make "near zero" really zero:

    logcl = abs(sig(:)) >= zero_tolerance;
    

    Then find regions where the cumulative sum isn't increasing:

    cs = cumsum(logcl);
    islands = cs(1+thresh:end) == cs(1:end-thresh);
    

    Remembering gnovice's great method for filling in ranges of indexes

    v = zeros(1,max(endInd)+1);   %# An array of zeroes
    v(startInd) = 1;              %# Place 1 at the starts of the intervals
    v(endInd+1) = v(endInd+1)-1;  %# Add -1 one index after the ends of the intervals
    indices = find(cumsum(v));  %# Perform a cumulative sum and find the nonzero entries
    

    We note that our islands vector already has ones in the startInd locations, and for our purposes endInd always comes thresh spots later (longer runs have runs of ones in islands)

    endcap = zeros(thresh,1);
    indices = find(cumsum([islands ; endcap] - [endcap ; islands]))
    

    Test

    sig = [1 1 0 0 0 0 1 1 1 1 1 0 1 0 0 0 1 1 1 1 1 1 1 1 0 0 1 1 1 0];
    logcl = abs(sig(:)) >= .1;
    cs = cumsum(logcl);
    islands = cs(1+thresh:end) == cs(1:end-thresh);
    endcap = zeros(thresh,1);
    indices = find(cumsum([islands ; endcap] - [endcap ; islands]))
    
    indices =
    
         2
         3
         4
         5
        13
        14
        15
    

提交回复
热议问题