AppDividend
Latest Code Tutorials

# Numpy diag_indices: How to Use np diag_indices() in Python

The diag_indices() method returns the indices to access the main diagonal of the array. That returns a tuple of indices that can be used to access the main diagonal of an array a with the a.ndim >= 2 dimensions and shape (n, n, …, n).

## Numpy diag_indices()

Numpy diag_indices() method returns the indices of the main diagonal in the form of tuples. These indices are further used for accessing the main diagonal of an array with minimum dimension 2. For a.ndim = 2 this is a usual diagonal and for a.ndim > 2, this is the set of indices to access a[i, i, …, i] for i = [0..n-1].

### Syntax

`numpy.diag_indices(n, ndim=2)`

### Parameters

n:(int)

The size along each dimension of the arrays for which indices of the main diagonal is required.

ndim:(int,optional)

The number of dimensions. It by default 2.

### Return Value

It returns a tuple consisting of the indices of the main diagonal of the array. This tuple can further be used for accessing the main diagonal elements.

### Example

```# app.py

import numpy as np

# create an array of size 5x5
n = np.diag_indices(5)
print(n)
a = np.arange(16).reshape(4, 4)
print('intial array:', a)
d = np.diag_indices(4)
a[d] = 25
print('new array:', a)```

#### Output

```python3 app.py
(array([0, 1, 2, 3, 4]), array([0, 1, 2, 3, 4]))
intial array: [[ 0  1  2  3]
[ 4  5  6  7]
[ 8  9 10 11]
[12 13 14 15]]
new array: [[25  1  2  3]
[ 4 25  6  7]
[ 8  9 25 11]
[12 13 14 25]]```

## #Program for diag_indices() function in Python

Write a program to print indices of the main diagonal of the NxN array and make its diagonal item to m.

```# app.py

import numpy as np

n = input("enter the size of array:")
data = int(n)

print("indices of main diagonal:")
array = np.diag_indices(data)
print(array)

a = np.arange(data * data).reshape(data, data)
print("old array: \n", a)

d = np.diag_indices(data)
m = input("enter the element to insert on main diagonal:")
a[d] = m

print("new array: \n", a)
```

#### Output

```python3 app.py
enter the size of array:4
indices of main diagonal:
(array([0, 1, 2, 3]), array([0, 1, 2, 3]))
old array:
[[ 0  1  2  3]
[ 4  5  6  7]
[ 8  9 10 11]
[12 13 14 15]]
enter the element to insert on main diagonal:25
new array:
[[25  1  2  3]
[ 4 25  6  7]
[ 8  9 25 11]
[12 13 14 25]]```

Here we are getting the indices of the main diagonal of NxN array, and we are using those indices to change the values of the main diagonal.

We have entered the different sizes of the arrays and the value to be inserted on the main diagonal. We are creating different NxN arrays and inputting the values from 0 to (N^2)-1. We are displaying the indices of the main diagonal first after that the array, and in the end, we are displaying the modified array.