VOOZH about

URL: https://www.geeksforgeeks.org/python/python-numpy-matrix-sum/

⇱ Python | Numpy matrix.sum() - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python | Numpy matrix.sum()

Last Updated : 17 Nov, 2025

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().


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.


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.


Output
[[10 15 20]]

Explanation: m.sum(axis=0) sums column-wise (2+1+7), (4+3+8), (6+5+9)

Comment