Getting the diagonals of a matrix using NumPy

The main diagonal of a matrix is constituted by the elements whose row number is equal to the column number. The diagonal() function of the numpy.linalg module returns the specific diagonal of a given matrix.

Linear Algebra Updated 12 Apr 2025 1 min read

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

python
# 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

Output
Rectangular matrix:

            [[-5 -4 -3 -2]

             [-1  0  1  2]

             [ 3  4  5  6]]

            Main diagonal of the rectangular matrix:

            [-5  0  5]