Numpy sum over planes of 3d array, return a scalar

numpy

Solution

You can do

sum_vec = np.array([plane.sum() for plane in cube])

or simply

sum_vec = cube.sum(-1).sum(-1)

where `cube` is your 3d array. You can specify `0` or `1` instead of `-1` (or `2`) depending on the orientation of the planes. The latter version is also better because it doesn't use a Python loop, which usually helps to improve performance when using `numpy`.

Problem

I'm making the transition from MATLAB to Numpy and feeling some growing pains. I have a 3D array, lets say it's 3x3x3 and I want the scalar sum of each plane. In matlab, I would use: ``` sum_vec = sum(3dArray,3); ``` TIA wbg EDIT: I was wrong about my matlab code. Matlab only vectorizes in one dim, so a loop wold be required. So numpy turns out to be more elegant...cool. ``` MATLAB for i = 1:3 sum_vec(i) = sum(sum(3dArray(:,:,i)); end ```

Original source