how to create or expand an identity-like matrix in python

Viewed 29

I'm trying to creating a matrix like this:

[[A 0 0], 
 [0 B 0],
 [0 0 C]]

in which A,B,C could be either a submatrix or a constant

suppose I got one of the submatrix first:

[[1 2], 
 [3 4]]

then got the next:

[[5 0 0], 
 [0 6 0],
 [0 0 7]]

How can I concat them into the format like below?

[[1 2 0 0 0],
 [3 4 0 0 0],
 [0 0 5 0 0], 
 [0 0 0 6 0],
 [0 0 0 0 7]]
1 Answers

You can simply use scipy.linalg.block_diag

As follow:

from scipy.linalg import block_diag
A = [[1, 2], [3, 4]]
B = [[5, 0, 0], 
     [0, 6, 0],
     [0, 0, 7]]

block_diag(A, B)

Output:

array([[1, 2, 0, 0, 0],
       [3, 4, 0, 0, 0],
       [0, 0, 5, 0, 0],
       [0, 0, 0, 6, 0],
       [0, 0, 0, 0, 7]])
Related