1

If the size of the matrix is (3, 4, 4);

new_matrix = matrix[0] + matrix[1] + matrix[2]

How can I do element-wise addition of each element of the matrix.'

Example:

matrix = np.array([[[1, 2], [3, 4]], [[4, 5], [6, 7]], [[8, 9], [10, 11]]])

new_matrix = np.zeros(shape=(2, 2))

for i in range(matrix.shape[0]):
    new_matrix += matrix[i]

print(new_matrix)

Answer: [[13, 16], [19, 22]]

Question: How would I do without for loop?

1 Answer 1

1

You can use np.sum function available in numpy. You can specify the axis along which you want to perform addition otherwise it will give the total sum of all elements in the matrix.

For your example,

matrix = np.array([[[1, 2], [3, 4]], [[4, 5], [6, 7]], [[8, 9], [10, 11]]])
print(np.sum(matrix,axis=0))

The output is

[[13 16]
 [19 22]]

This is the link for np.sum documentation: np.sum

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

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.