Home »
Python »
Linear Algebra using Python
Python | Diagonal of a Matrix
Diagonal of a Matrix in Python: Here, we will learn about the diagonal of a matrix and how to find it using Python code?
Submitted by Anuj Singh, on July 17, 2020
Some problems in linear algebra are mainly concerned with diagonal elements of the matrix. For this purpose, we have a predefined function numpy.diag(a) in NumPy library package which automatically stores diagonal elements in an array (a Vector). In this article, we are going to print the diagonal elements of a matrix using inbuilt function numpy.diag(a).
Python code to find diagonal of a matrix
# Linear Algebra Learning Sequence
# Diagonal of matrix
import numpy as np
print('Diagonal of an 3x3 identity matrix : ', np.diag(np.eye(3)))
a = np.arange(9).reshape((3,3))
print(' Matrix a : ', a)
print('Diagonal of Matrix a : ', np.diag(a))
Output:
Diagonal of an 3x3 identity matrix : [1. 1. 1.]
Matrix a : [[0 1 2]
[3 4 5]
[6 7 8]]
Diagonal of Matrix a : [0 4 8]