# What is the numpy.diag() Method

Numpy.diag() method is “used to extract and construct a diagonal array.”

## Syntax

``````numpy.diag(arr,k)
``````

## Parameters

It takes two parameters, out of which one parameter is optional.

1. arr: It is an input array
2. k: It is optional and takes 0 by default. If the value of this parameter is greater than 0, it means the diagonal is above the main diagonal, and vice versa if it is not.

## Return Value

It returns an array with a diagonal array.

## Example 1: How to Use numpy.diag() Method

``````import numpy as np

a = np.matrix([[1, 2, 3], [4, 5, 6], [9, 8, 7]])

print("Main Diagonal: \n", np.diag(a), "\n")

print("Above main diagonal: \n", np.diag(a, 1),
"\n") # k=1 (for above main diagonal)

print("Below main diagonal: \n", np.diag(a, -1)) # k=-1 (for below main diagonal)

``````

Output

``````Main Diagonal: [1 5 7]

Above main diagonal: [2 6]

Below main diagonal: [4 8]``````

## Example 2: How does the np.diag() Method work?

``````import numpy as np

a = np.matrix([[1, 2, 3], [4, 5, 6], [9, 8, 7], [11, 13, 15]])

print("Main Diagonal: \n", np.diag(a), "\n")

# k=1 (for above main diagonal)
print("Above main diagonal: \n", np.diag(a, 1), "\n")

# k=-1 (for below main diagonal)
print("Below main diagonal: \n", np.diag(a, -1))``````

Output

``````Main Diagonal:
[1 5 7]

Above main diagonal:
[2 6]

Below main diagonal:
[ 4 8 15]``````

## Example 3: Use a 4×4 Matrix and Apply the diag() Function

``````import numpy as np

# Define a 4x4 matrix
matrix = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]])

print("Original Matrix:")
print(matrix)

# Extract the diagonal elements
diagonal = np.diag(matrix)

print("\nDiagonal Elements:")
print(diagonal)``````

Output

``````Original Matrix:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]]

Diagonal Elements:
[ 1 6 11 16]
``````

## Example 4: Use Construct Diagonal From Python NumPy Array

By using numpy.diag() function, we can also create a matrix with diagonal values.

``````import numpy as np

arr = np.array([11, 19, 21, 46])

arr2 = np.diag(arr)
print(arr2)
``````

Output

``````[[11 0 0 0]
[ 0 19 0 0]
[ 0 0 21 0]
[ 0 0 0 46]]
``````

That’s it.

This site uses Akismet to reduce spam. Learn how your comment data is processed.