Python | Numpy matrix.sum()
matrix.sum() is a NumPy function used to calculate the sum of all elements in a matrix. It can also compute row-wise and column-wise sums using the axis parameter. This method works only with NumPy matrix objects, not arrays.
Example:
Input: [[1, 2], [3, 4]]
Output: 10
Syntax
matrix.sum(axis=None)
Parameter: axis (Optional) -
- None: sum of all elements
- 0: column-wise sum
- 1: row-wise sum
Examples
Example 1: This example creates a 2×2 matrix using np.matrix and computes the sum of all its elements using matrix.sum().
import numpy as np
m = np.matrix([[4, 1],
[12, 3]])
out = m.sum()
print(out)
Output
20
Explanation: m.sum() adds all elements (4 + 1 + 12 + 3 = 20).
Example 2: This example calculates the sum of each row separately by setting axis=1.
import numpy as np
m = np.matrix([[4, 1, 9],
[12, 3, 1],
[4, 5, 6]])
out = m.sum(axis=1)
print(out)
Output
[[14] [16] [15]]
Explanation: m.sum(axis=1) sums each row individually.
Example 3: This example finds the sum of each column in a 3×3 matrix using axis=0.
import numpy as np
m = np.matrix([[2, 4, 6],
[1, 3, 5],
[7, 8, 9]])
out = m.sum(axis=0)
print(out)
Output
[[10 15 20]]
Explanation: m.sum(axis=0) sums column-wise (2+1+7), (4+3+8), (6+5+9)