Matlab cumsum是否在NaN重置? [英] Matlab cumsum reset at NaN?

查看:141
本文介绍了Matlab cumsum是否在NaN重置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的矢量是1或NaN这样的话:

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]

如何在NaN的位置将累积量重置为零,如下所示:

How can I reset the cumsum to zero at the location of the NaNs like below:

[1 2 3 0 1 2 0 1 2 3 4]

理想情况下,我想有一个矢量化的解决方案,因为我需要对大型矩阵中的每一列都执行此操作,并且NaN的位置在各列中不是恒定的.

Ideally I would like to have a vectorized solution since I need to do this for every column in a large matrix and the locations of the NaNs are not constant across the columns.

谢谢.

推荐答案

我只能想到几个通过的解决方案:

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]

注意:尚未检查极端条件(NaN在第一/最后位置,连续的NaN s等)

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

这篇关于Matlab cumsum是否在NaN重置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆