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!

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.