monte carlo
monte carlo

Reputation: 95

insert matrix into the center of another matrix in python

Is there any fast and simple way to insert a small matrix into the center (or any other x,y index) of another, biger matrix using numpy or scipy?
That is, say I have matrix

A = [1 2]
    [3 4]

and matrix

B =   [0 0 0 0 0 0]  
      [0 0 0 0 0 0]  
      [0 0 0 0 0 0]  
      [0 0 0 0 0 0]  
      [0 0 0 0 0 0]  
      [0 0 0 0 0 0]  

I want to insert A into the center of B as so:

C =   [0 0 0 0 0 0]  
      [0 0 0 0 0 0]  
      [0 0 1 2 0 0]  
      [0 0 3 4 0 0]  
      [0 0 0 0 0 0]  
      [0 0 0 0 0 0] 

Upvotes: 7

Views: 8343

Answers (1)

sangrey
sangrey

Reputation: 488

You can use numpy's slice notation.

nb = B.shape[0]
na = A.shape[0]
lower = (nb) // 2 - (na // 2)
upper = (nb // 2) + (na // 2)
B[lower:upper, lower:upper] = A

Upvotes: 12

Related Questions