0

Suppose, I got a 2D (n \times 2*n) numpy array like below,

dat = np.array([[1,2,3,4],[5,6,7,8]])

I want to split it into two 2d array equally, and then create a 2d diagonal block array, like below,

a = dat[:,0:2]
b = dat[:,2:]
result = np.block([
    [a,               np.zeros((2, 2))],
    [np.zeros((2, 2)), b              ]
])

Is there any better way in numpy that I dont need to specify this part "np.zero((n,n))"

0

1 Answer 1

2

Use scipy.linalg.block_diag

>>> import scipy.linalg
>>> scipy.linalg.block_diag(a, b)
array([[1, 2, 0, 0],
       [5, 6, 0, 0],
       [0, 0, 3, 4],
       [0, 0, 7, 8]])

Taken from this post

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.