How to replace sub part of matrix by another small matrix in NumPy?

Learn, how can we replace sub part of matrix by another small matrix in NumPy?
By Pranit Sharma Last updated : December 25, 2023

Problem statement

Suppose that we are given a numpy matrix and we need to replace a small part of this matrix with another small matrix.

NumPy - Replacing sub part of matrix by another small matrix

Replacing sub part of matrix by another small matrix can be simply done using the indexing, we just need to select the piece of the matrix that we need to replace which must be of the same shape as the small matrix, and assign this piece of the matrix as the small matrix.

Let us understand with the help of an example,

Python code to replace sub part of matrix by another small matrix in NumPy

# Import numpy
import numpy as np

# Creating an array
arr = np.ones((5,5))

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

# Creating a small matrix
small = np.array([[ 0.1,  0.2],[ 0.3,  0.4]])

# Display small matrix
print("Small matrix:\n",small,"\n")

# replacing a part of big matrix with small matrix
arr[3:5, 3:5] = small

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

Output

Example: How to replace sub part of matrix by another small matrix in NumPy?

Python NumPy Programs »


Comments and Discussions!

Load comments ↻






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