Python NumPy - Sum of Diagonals of NxN Identity Matrix

By IncludeHelp Last updated : September 11, 2024

Problem Statement

Given an NxN identity matrix, write a Python program to find the sum of its diagonals using NumPy.

Finding Sum of Diagonals of NxN Identity Matrix

To find the sum of diagonals of nxn identity matrix, we can create a function which will first create an n x n identity matrix using numpy.identity(), and then computes the sum of its diagonal elements using the numpy.trace() function. Finally, it returns the sum of the diagonal elements.

Python Code to Find Sum of Diagonals of NxN Identity Matrix

Let us understand with the help of an example:

# Importing numpy
import numpy as np

# Defining a function
def fun(n):
    identity_matrix = np.identity(n)
    diagonal_sum = np.trace(identity_matrix)
    return identity_matrix,diagonal_sum

# Defining a value for n
n = 5

# Display result
print("Identity is:\n",fun(n)[0],"\n")
print("Sum of diagonals is is:\n",fun(n)[1],"\n")

Output

The output of the above program is:

Identity is:
 [[1. 0. 0. 0. 0.]
 [0. 1. 0. 0. 0.]
 [0. 0. 1. 0. 0.]
 [0. 0. 0. 1. 0.]
 [0. 0. 0. 0. 1.]] 

Sum of diagonals is is:
 5.0 

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.