Free cookie consent management tool by TermsFeed Getting the diagonals of a matrix using NumPy | Pythontic.com

Getting the diagonals of a matrix using NumPy

Overview:

  • The NumPy function diag() returns the main specified diagonal of a matrix.

  • For square matrices, the line of elements running from the top-left corner of the matrix to the bottom-right corner of the matrix is called the main diagonal of the matrix.

  • For rectangular matrices the line connecting the elements whose row number is equal to the column number is called the main diagonal.

  • The main diagonal is also referred to as principal diagonal, leading diagonal, primary diagonal and major diagonal.

  • The sum of elements of the main diagonal of a square matrix is called the trace of a matrix.

  • The determinant of a matrix is computed by LU decomposition method. Using LU decomposition method, the lower triangular matrices and upper triangle matrices of a matrix A are obtained and the elements along the main diagonal of both the matrices are multiplied to get the determinant of a matrix.

Main diagonal of a matrix

Example - Get the diagonal of a rectangular matrix:

# Example Python program that returns the main diagonal of a
# rectangular matrix using the numpy.linalg function diag()
import numpy

# Create a rectangular matrix of order 3x4
elems         = numpy.arange(-5, 7)
rectMatrix  = elems.reshape(3, 4)
print("Rectangular matrix:")
print(rectMatrix)

print("Main diagonal of the rectangular matrix:")
print(numpy.linalg.diagonal(rectMatrix))

Output:

Rectangular matrix:
[[-5 -4 -3 -2]
 [-1  0  1  2]
 [ 3  4  5  6]]
Main diagonal of the rectangular matrix:
[-5  0  5]

 


Copyright 2025 © pythontic.com