1

Is there an easier way to get the sum of all values (assuming they are all numbers) in an ndarray :

import numpy as np

m = np.array([[1,2],[3,4]])

result = 0
(dim0,dim1) = m.shape
for i in range(dim0):
    for j in range(dim1):
        result += m[i,j]

print result

The above code seems somewhat verbose for a straightforward mathematical operation.

Thanks!

Ohad Dan
  • 1,929
  • 5
  • 17
  • 22

2 Answers2

4

Just use numpy.sum():

result = np.sum(matrix)

or equivalently, the .sum() method of the array:

result = matrix.sum()

By default this sums over all elements in the array - if you want to sum over a particular axis, you should pass the axis argument as well, e.g. matrix.sum(0) to sum over the first axis.

As a side note your "matrix" is actually a numpy.ndarray, not a numpy.matrix - they are different classes that behave slightly differently, so it's best to avoid confusing the two.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
ali_m
  • 71,714
  • 23
  • 223
  • 298
1

Yes, just use the sum method:

result = m.sum()

For example,

In [17]: m = np.array([[1,2],[3,4]])

In [18]: m.sum()
Out[18]: 10

By the way, NumPy has a matrix class which is different than "regular" numpy arrays. So calling a regular ndarray matrix causes some cognitive dissonance. To help others understand your code, you may want to change the name matrix to something else.

Community
  • 1
  • 1
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677