Matlab cumsum reset at NaN?

前端 未结 3 975
借酒劲吻你
借酒劲吻你 2021-01-12 16:16

If I have a vector of either 1\'s or NaN\'s like this:

[1 1 1 NaN 1 1 NaN 1 1 1 1]

How can I reset the cumsum to zero at the location of th

3条回答
  •  遥遥无期
    2021-01-12 16:53

    You can try the following two 'vectorized' lines:

    A(isnan(A)) = 1-diff([0 find(isnan(A))]);
    cumsum(A)
    
    ans =
    
      1     2     3     0     1     2     0     1     2     3     4
    

    The trick is to substitute NaN with a value that will reset cumsum to 0 at those points.

提交回复
热议问题