numpy.diag() in Python
numpy.diag() in Python
The diag() function of Python numpy class extracts and construct a diagonal array.
Syntax
numpy.diag(v, k=0)
Parameter
a: It represents the array_like.
k: It represents the diagonal value that we require. It is an optional parameter and its default value is 0. If k>0, the diagonal is above the main diagonal or vice versa.
Return
This function returns the extracted diagonal or constructed diagonal array.
Example 1
# Python Programming explaining
# numpy.diag() function
import numpy as np
# matrix creation by array input
num = np.matrix([[11, 121, 130],
[613 ,34, 13],
[514, 50, 16]])
print("Main Diagnol elements : \n", np.diag(num))
print("\nDiagnol elements above main diagnol : \n", np.diag(num, 1) )
print("\nDiagnol elements below main diagnol : \n", np.diag(num, -1))
Output
Main Diagnol elements : [11 34 16] Diagnol elements above main diagnol : [121 13] Diagnol elements below main diagnol : [613 50]
