Reputation: 79
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?
Upvotes: 1
Views: 114
Reputation: 983
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
Upvotes: 1