AppDividend
Latest Code Tutorials

# Python NumPy diag() Function Example

Python numpy diag() is an inbuilt NumPy function that extracts and construct a diagonal array. NumPy diag() function contains two parameters and is used to extract and create a diagonal array from the given array. It is defined under numpy, which can be imported as import numpy as np, and we can create multidimensional arrays and derive other mathematical statistics with the help of numpy, which is a library in Python. Diag() name is also derived from diagonal.

## Python NumPy diag()

Python numpy diag() function extracts and construct a diagonal array.

### Syntax

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

### Parameters

It takes 2 parameters out of which 1 parameter is optional.

The first parameter is the array input represented by arr. The second parameter is k, which is optional and takes value 0 by default. If the value of this parameter is greater than 0, it means diagonal is above the main diagonal and vice versa if it is not.

### Return Value

It returns an array with a diagonal array.

### Example programs on diag() method in Python

Write a program to show the working of diag() function in Python.

```# app.py

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]

```

In this example, we can see that by using numpy diag(), we can see that by passing different values of k, we can get their diagonal elements. Here we saw what is the main diagonal in the matrix, then the diagonal above the main diagonal by passing value k=1 and vice versa by passing value k=-1.

#### Example 2: Write a program to take a 4×4 matrix and then apply the diag() function.

See the following code.

```# app.py

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

```python3 app.py
Main Diagonal:
[1 5 7]

Above main diagonal:
[2 6]

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

In this example, we passed a 4×4 matrix and got the required output of the main diagonal, above the main diagonal ( k=1) and below the main diagonal(k=-1).