Change the values of the diagonal of a NumPy matrix

Learn, how to change the values of the diagonal of a NumPy matrix in Python?
By Pranit Sharma Last updated : December 27, 2023

Diagonals of an array are defined as a set of those points where the row and the column coordinates are the same.

Changing the values of the matrix's diagonal

To change the values of a diagonal of a matrix, we can use numpy.diag_indices_from() to get the indices of the diagonal elements of your array. Then set the value of those indices, we can simply assign them any value we want.

Let us understand with the help of an example,

Python code to change the values of the diagonal of a NumPy matrix

# Import numpy
import numpy as np

# Creating a numpy array
arr = np.random.rand(5, 5)

# Display original data
print("Original data:\n",arr,"\n")

# Getting diagonal indices
ind = np.diag_indices_from(arr)

# Giving the diagonals some value
arr[ind] = 0

# Display result
print("Result:\n",arr,"\n")

Output

Example: Change the values of the diagonal of a NumPy matrix

In this example, we have used the following Python basic topics that you should learn:

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.