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]





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.