Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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] 
like image 270
monte carlo Avatar asked Nov 27 '16 19:11

monte carlo


1 Answers

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
like image 51
sangrey Avatar answered Nov 03 '22 06:11

sangrey