Numpy diag() Function



The Numpy diag() function is used to either extract the diagonal elements from a matrix (2D array) or create a diagonal matrix from a 1D array or list. This function is used in matrix operations and numerical computations.

The numpy.diag() function can be used in two different ways:

  • In case of 2D array, the function extracts the diagonal elements of the array.
  • In case of 1D array, the function creates a square diagonal matrix with the elements of the 1D array as the diagonal values and zeros in reamining positions.

Syntax

Following is the syntax of the Numpy diag() function −

numpy.diag(array, k=0)

Parameters

Following are the parameters of the Numpy diag() function −

  • array: This represents input array(can be array_like)
  • k(Optional): This is an integer number representing the diagonal to retrieve −
  • k>0 - represents diagonals above the main diagonal
  • k<0 - represents diagonals below the main diagonal

Return Value

The function either returns the diagonal elements of a 2D array or a new square 2D array (diagonal matrix) when provided with a 1D array.

Example

Following is a basic example to extract the diagonal elements from a given 2D array using Numpy diag() function −

import numpy as np
Matrix = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])
print("Original Array:\n", Matrix)
Diagonal_elements = np.diag(Matrix)
print("Diagonal Elements:", Diagonal_elements)

Output

Following is the output of the above code:

Original Array:
 [[10 20 30]
 [40 50 60]
 [70 80 90]]
Diagonal Elements: [10 50 90]

Example : Creating a Diagonal Matrix

When a 1D array is passed to the numpy.diag() function, it creates a square matrix with the elements of the array on the main diagonal and zeros elsewhere.

In the following example, we have created a diagonal matrix from a given 1D array −

import numpy as np
array = np.array([1, 2, 3, 4])
print("Original Array:",array)
diagonal_matrix = np.diag(array)
print("Diagonal Matrix:\n", diagonal_matrix)

Output

Following is the output of the above code −

Original Array: [1 2 3 4]
Diagonal Matrix:
 [[1 0 0 0]
 [0 2 0 0]
 [0 0 3 0]
 [0 0 0 4]]

Example : Specifying Diagonal Offset

The k parameter can be used to specify which diagonal to extract or set. Positive values extract diagonals above the main diagonal, while negative values extract diagonals below the main diagonal.

'k' with Positive Integer

In the following example, we have extracted the diagonal elements that is one step above the main diagonal (k=1) −

import numpy as np
matrix = np.array([[11, 22, 33], [44, 55, 66], [77, 88, 99]])
print("Original Array:\n",matrix)
diagonal_above = np.diag(matrix, k=1)
print("Diagonal Above Main Diagonal:", diagonal_above)

Output

Following is the output of the above code −

Original Array:
 [[11 22 33]
 [44 55 66]
 [77 88 99]]
Diagonal Above Main Diagonal: [22 66]

'k' with Negative Integer

In the following example, we have created a diagonal matrix where the diagonal is one step below the main diagonal (k=-1) −

import numpy as np
array = np.array([[11, 22, 33], [44, 55, 66], [77, 88, 99]])
print("Original Array:\n",array)
diagonal_matrix_below = np.diag(array, k=-1)
print("Diagonal Matrix Below Main Diagonal:", diagonal_matrix_below)

Output

Following is the output of the above code −

Original Array:
 [[11 22 33]
 [44 55 66]
 [77 88 99]]
Diagonal Matrix Below Main Diagonal: [44 88]

Example : Specifying Different Data Types

We can specify the data type of the elements in the diagonal matrix by setting the dtype attribute when creating the array before passing it to numpy.diag().

In the following example, we have created a diagonal matrix of float data type −

import numpy as np
Float_array = np.array([10, 20, 30], dtype=float)
Float_diagonal_matrix = np.diag(Float_array)
print("Float Diagonal Matrix:\n", Float_diagonal_matrix)

Output

Float Diagonal Matrix:
 [[10.  0.  0.]
 [ 0. 20.  0.]
 [ 0.  0. 30.]]

Example : Passing a Float value for 'k'

When we provide a non-integer value for the k parameter or pass invalid data types, numpy.diag() will raise TypeError.

In the following example, we have passed the k value as a float point which resulted an error −

import numpy as np
array = np.array([1, 2, 3])
# This will raise a TypeError
diagonal_matrix_float_k = np.diag(array, k=1.5)
print(diagonal_matrix_float_k)

Output

Traceback (most recent call last):
  File "/home/cg/root/46524/main.py", line 4, in <module>
    diagonal_matrix_float_k = np.diag(array, k=1.5)
  File "<__array_function__ internals>", line 200, in diag
  File "/usr/local/lib/python3.10/dist-packages/numpy/lib/twodim_base.py", line 299, in diag
    res = zeros((n, n), v.dtype)
TypeError: 'float' object cannot be interpreted as an integer
numpy_array_creation_routines.htm
Advertisements