wbg
wbg

Reputation: 918

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

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

Upvotes: 3

Views: 9789

Answers (5)

nrc
nrc

Reputation: 143

If you're trying to sum over a plane (and avoid loops, which is always a good idea) you can use np.sum and pass two axes as a tuple for your argument. For example, if you have an (nx3x3) array then using

np.sum(a, (1,2))

Will give an (nx1x1), summing over a plane, not a single axis.

Upvotes: 0

Frank Hahn
Frank Hahn

Reputation: 3

sumvec= np.sum(3DArray, axis=2)

or this works as well

sumvec=3DArray.sum(2)

Remember Python starts with 0 so axis=2 represent the 3rd dimension.

https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.sum.html

Upvotes: 0

nickpapior
nickpapior

Reputation: 782

Instead of applying the same sum function twice, you may perform the sum on the reshaped array:

a = np.random.rand(10, 10, 10) # 3D array
b = a.view()
b.shape = (a.shape[0], -1)
c = np.sum(b, axis=1)

The above should be faster because you only sum once.

Upvotes: 0

tiago
tiago

Reputation: 23492

You should use the axis keyword in np.sum. Like in many other numpy functions, axis lets you perform the operation along a specific axis. For example, if you want to sum along the last dimension of the array, you would do:

import numpy as np
sum_vec = np.sum(3dArray, axis=-1)

And you'll get a resulting 2D array which corresponds to the sum along the last dimension to all the array slices 3dArray[i, k, :].

UPDATE

I didn't understand exactly what you wanted. You want to sum over two dimensions (a plane). In this case you can do two sums. For example, summing over the first two dimensions:

sum_vec = np.sum(np.sum(3dArray, axis=0), axis=0)

Upvotes: 4

Lev Levitsky
Lev Levitsky

Reputation: 65791

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.

Upvotes: 7

Related Questions