The diag()
function in Python is used to extract a diagonal array.
numpy.diag(v, k=0)
The diag()
function takes the following parameter values:
v
: This represents the array_like
object.k
: This represents the diagonal in question. The default is 0
. k>0
for diagonals above the main diagonal and k<0
for diagonals below the main diagonal.The diag()
function returns a constructed diagonal array or an extracted diagonal array.
import numpy as np# creating an arraymyarray = np.arange(9).reshape((3,3))# implementing the diag() functiondiagarray = np.diag(myarray, k=0)print(myarray)print(diagarray)
numpy
library.myarray
that contains 9
values with a dimension of 3x3 (3
rows and 3
columns) using the arange()
function.diag()
function on the array myarray
using the main diagonal k=0
. The result is assigned to a new variable, diagarray
.myarray
.diagarray
.