How do you sum all the elements in an array?
>>> import Numeric
>>> a = Numeric.array([1, 5, -3, 2, -9])
sum does the summation along the array's
index 0 axis, and thus returns an array with that dimension "removed".
Thus, for a 2-D array, it sums down columns, and returns a vector
with a length equal to the number of columns of the original array:
>>> b = Numeric.array( [[1,5,-3,2,-9], [4,6,-2,6,8]] )
array([[ 1, 5, -3, 2, -9],
[ 4, 6, -2, 6, 8]])
array([ 5, 11, -5, 8, -1])
You can change which axis to sum over
>>> Numeric.sum(b, axis=1)
To sum all the elements in the array, you'll need to apply
raveled version of the array.
ravel is the better choice since it works
on all arrays, where
flat only works on contiguous arrays:
>>> Numeric.sum( b.flat )
>>> Numeric.sum( Numeric.ravel(b) )
sum is an alias for
in IDL provides
similar functionality, though for
default is to sum over the entire array, not just the first axis.
Notes: See also Martelli (2003), pp. 324, 326.