How do I vectorize this cumulative operation?

Let be `W`

some matrix of dimension `(x, nP)`

[see. end of question]

I am currently doing the following code:

``````uUpperDraw = np.zeros(W.shape)
for p in np.arange(0, nP):
uUpperDraw[s, p] = (W[s+1,:(p+1)]).sum()
```

(adsbygoogle = window.adsbygoogle || []).push({});

```

I want to vectorize this for efficiency. Given `pGrid = [0, 1, ...]`

how can I reproduce the following?

``````uUpperDraw = np.array([sum(W[x, 0]), sum(W[x,0] + W[x, 1]), sum(W[x,0] + W[x, 1] + W[x, 2]) ...
```

(adsbygoogle = window.adsbygoogle || []).push({});

```

Here are some reproducible examples.

``````>>> s, nP
(3, 10)
>>> W

array([[ 0.        ,  0.        ,  0.        ,  0.        ,  0.        ,
0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
[ 0.        ,  0.        ,  0.        ,  0.        ,  0.        ,
0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
[ 0.        ,  0.        ,  0.        ,  0.        ,  0.        ,
0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
[ 0.        ,  0.        ,  0.        ,  0.        ,  0.        ,
0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
[ 2.        ,  1.63636364,  1.38461538,  1.2       ,  1.05882353,
0.94736842,  0.85714286,  0.7826087 ,  0.72      ,  0.66666667]])
>>> uUpperDraw
array([[  0.        ,   0.        ,   0.        ,   0.        ,
0.        ,   0.        ,   0.        ,   0.        ,
0.        ,   0.        ],
[  0.        ,   0.        ,   0.        ,   0.        ,
0.        ,   0.        ,   0.        ,   0.        ,
0.        ,   0.        ],
[  0.        ,   0.        ,   0.        ,   0.        ,
0.        ,   0.        ,   0.        ,   0.        ,
0.        ,   0.        ],
[  2.        ,   3.63636364,   5.02097902,   6.22097902,
7.27980255,   8.22717097,   9.08431383,   9.86692252,
10.58692252,  11.25358919],
[  0.        ,   0.        ,   0.        ,   0.        ,
0.        ,   0.        ,   0.        ,   0.        ,
0.        ,   0.        ]])
```

(adsbygoogle = window.adsbygoogle || []).push({});

```
+3

source to share

1 answer

It looks like a cumulative amount. If you want the cumulative sum for each row separately, works here

``````uUpperDraw = np.cumsum(W,axis=1)
```

(adsbygoogle = window.adsbygoogle || []).push({});

```
+5

source

All Articles