get the sum of diagonal elements in a numpy array

Numpy – Get the Sum of Diagonal Elements

The Numpy library in Python comes with a number of useful functions to work with and manipulate the data in arrays. In this tutorial, we will look at how to get the sum of the diagonal elements of a 2d array in Numpy.

How to get the sum of diagonal elements in Numpy?

get the sum of diagonal elements in a numpy array

To get the sum of diagonal elements of a 2d Numpy array, first, use the numpy.diag() function to get the diagonal elements and then calculate their sum using numpy.ndarray.sum().

The following is the syntax –

numpy.diag(v, k).sum()

The numpy.diag() function takes the following parameters –

  1. v – The 2d array to extract the diagonal elements from.
  2. k – The diagonal to extract the elements from. It is 0 (the main diagonal) by default. Diagonals below the main diagonal have k < 0 and the ones above the main diagonal have k > 0.

It returns the extracted elements from the diagonal as a numpy array.

You can then apply the numpy.ndarray.sum() function on the returned array of diagonal elements to get its sum.

Examples

Let’s now look at examples of using the above syntax to get the sum of diagonal elements of a 2d array.

First, we will create a Numpy array that we will use throughout this tutorial.

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

import numpy as np

# create a 2D numpy array
arr = np.array([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
    [10, 11, 12]
])
# display the matrix
print(arr)

Output:

[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]]

Here, we used the numpy.array() function to create a 2d array of shape 4×3 (having 4 rows and 3 columns).

Example 1 – Sum of elements on the default diagonal

Let’s now use the numpy.diag() function to get the diagonal elements for the 2d array created above. We will use the default diagonal (k = 0).

# get the diagonal elements
res = np.diag(arr)
# display the diagonal elements
print(res)

Output:

[1 5 9]

We get the diagonal elements of the passed array as a 1d numpy array. You can see that the returned array has the same values as the main diagonal.

To get the sum of the diagonal elements, use the numpy.ndarray.sum() function.

# get the sum of diagonal elements
print(res.sum())

Output:

15

We get the sum of the main diagonal elements as 15.

Example 2 – Sum of elements on a custom diagonal

In the above example, we extracted the elements of the main diagonal.

The numpy.diag() function comes with an optional parameter, k that you can use to specify the diagonal you want to extract the elements from.

The below image better illustrates the different values of k (representing different diagonals) for our input array.

k is 0 by default. The diagonals below the main diagonal have k < 0 and the diagonals above it have k > 0.

Let’s now use the numpy.diag() function to get the elements on diagonal, k = -1.

# get the elements of the diagonal -1
res = np.diag(arr, k=-1)
# display the diagonal elements
print(res)

Output:

[ 4  8 12]

We get the elements for the k=-1 diagonal.

Now, we’ll use the numpy.ndarray.sum() function to get its sum.

# get the sum of diagonal elements
print(res.sum())

Output:

24

We get the sum of values in the k=-1 diagonal as 24.

Summary

In this tutorial, we looked at how to get the sum of diagonal elements of a 2d array in Numpy. The following are the steps mentioned in this tutorial.

  1. Use the numpy.diag() function to get the diagonal elements of a 2d array. You can specify the diagonal for which you want the extract the elements using the optional parameter k. By default, it represents the main diagonal, k = 0.
  2. Once you have an array of the diagonal elements, use the numpy.ndarray.sum() function to get its sum.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

Scroll to Top