VOOZH about

URL: https://www.geeksforgeeks.org/python/calculate-the-sum-of-the-diagonal-elements-of-a-numpy-array/

⇱ Calculate the sum of the diagonal elements of a NumPy array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Calculate the sum of the diagonal elements of a NumPy array

Last Updated : 5 Sep, 2020

Sometimes we need to find the sum of the Upper right, Upper left, Lower right, or lower left diagonal elements. Numpy provides us the facility to compute the sum of different diagonals elements using numpy.trace() and numpy.diagonal() method.

Method 1: Finding the sum of diagonal elements using numpy.trace()

Syntax : numpy.trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None)  

Example 1: For 3X3 Numpy matrix

Output:

👁 Image

Example 2: For 4X4 Numpy matrix

Output:

👁 Image

Method 2: Finding the sum of diagonal elements using numpy.diagonal()

Syntax :

numpy.diagonal(a, offset=0, axis1=0, axis2=1

Example 1: For 3X3 Numpy Matrix

Output:

👁 Image

Example 2: For 5X5 Numpy Matrix

Output:

👁 Image
Comment