Alex
Alex

Reputation: 49

how to insert a matrix in the middle of another matrix

I am working in Python. I have a matrix called Y = np.random.rand(10,10) and a matrix called X=np.zeros ((5,5)). I define: y_insert=2 x_insert=3 I want to insert matrix X on Y on position (x_insert,y_insert). So the result should be a 10 by 10 matrix filled with random numbers except between (2,3) and (6,7) where the matrix should contain 0. How can that be achieved?

So far I have tried:

Y = np.random.rand(10,10)
X=np.zeros ((5,5))
y_insert=2
x_insert=3
insert matrix X on Y on position (x_insert,y_insert)

Upvotes: 0

Views: 233

Answers (1)

zvone
zvone

Reputation: 19362

All you need to do is address the sub-matrix of Y you want to override and then assign X to it:

Y[x_insert : x_insert + 5, y_insert : y_insert + 5] = X

Or, for a more general case:

Y[x_insert : x_insert + X.shape[0], y_insert : y_insert + X.shape[1]] = X

Upvotes: 2

Related Questions