numpy.diag() in Python
The diag() function of Python numpy class extracts and construct a diagonal array.
Syntax
1 2 3 |
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
1 2 3 4 5 6 7 8 9 10 11 12 |
# 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
1 2 3 4 5 6 7 8 |
Main Diagnol elements : [11 34 16] Diagnol elements above main diagnol : [121 13] Diagnol elements below main diagnol : [613 50] |