Matlab cumsum reset at NaN?

前端 未结 3 952
借酒劲吻你
借酒劲吻你 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 17:04

    I can only think of a few-pass solution:

    v = [1 1 1 NaN 1 1 1 1 NaN 1];
    a = v==v;              %% convert the values first to [1 1 1 0 1 1 1 1 0 1] format
    n = a==0;              %% positions of the NaNs
    c = cumsum(a);         %% your intermediate result
    d = diff([0 c(n)]);    %% runs of ones
    v(n) = -d;             %% replace Nans by -3, -4      [1 1 1 -3 1 1 1 1 -4 1] 
    cumsum(v)              %% the answer [1 2 3 0 1 2 3 4 0 1]
    

    Note: haven't checked extreme conditions (NaN in first/Last position, consecutive NaNs etc.)

提交回复
热议问题