Python

NumPy np.fill_diagonal()

This function in NumPy allows us to fill the main diagonal of a given array with the specified value in the function parameter.

Let us explore this function and how we can use it.

Function Syntax

The function syntax is as shown below:

numpy.fill_diagonal(a, val, wrap=False)

Parameters

The function parameters are discussed in the section below:

  1. a – refers to the input array whose diagonal is filled with the specified value.
  2. val – refers to the value that is filled in the diagonal of the input array. You can set the value as a scalar value or an array. If the value is a scalar, it is populated in the diagonal. An array is flattened and its elements populated in the diagonal of the input array. The function will repeat the elements of the array until the diagonals are filled.

NOTE: The fill_diagonal() function performs the operation in-place. This means that it will modify the original behavior instead of creating a new copy of the array.

Example #1

Take a look at the example shown below:

# import numpy
import numpy as np
# create array
arr = np.array([[1,2,3], [4,5,6]])
print(f"old array: {arr}")
np.fill_diagonal(arr, 0)
print(f"new array: {arr}")

In the example above, we use the fill_diagonal function to replace the main diagonal of the 2d array with zeros.

The code above should return output as shown:

old array:

[[1 2 3]
 [4 5 6]]
new array:
[[0 2 3]
 [4 0 6]]

Example #2

The example below uses an array to replace the diagonal elements in a 2d array.

arr = np.array([[1,2,3], [4,5,6]])
np.fill_diagonal(arr, [[100,100]])
print(arr)

In the above example, we pass a 2d array to fill the diagonal of a 2d array. The resulting array is as shown:

[[100   2   3]
 [  4 100   6]]

Example #3

You can also use this function to generate an identity matrix. An example is shown below:

arr = np.zeros((3, 3), int)
np.fill_diagonal(arr, 1)
print(arr)

And that should give us a matrix of zeros where the main diagonal is filled with ones.

[[1 0 0]
 [0 1 0]
 [0 0 1]]

Conclusion

That is it for this one. This article described the fill_diagonal() function as provided in NumPy. We also illustrated various examples of using the function.

Thanks for reading!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list