2

I have several matrices, let's say [M1,M2,M3,M4]. Each matrix has a different shape. How do I compose these matrices into one big matrix diagonally like:

[[M1, 0, 0, 0]
 [0, M2, 0, 0]
 [0, 0, M2, 0]
 [0, 0, 0, M2]]

Example:

M1 = [[1,2],[2,1]]
M2 = [[1,2]]
M3 = [[3]]
M4 = [[3,4,5],[4,5,6]]

To compose this big matrix:

[[1, 2, 0, 0, 0, 0, 0]
 [2, 1, 0, 0, 0, 0, 0]
 [0, 0, 1, 2, 0, 0, 0]
 [0, 0, 0, 0, 3, 4, 5]
 [0, 0, 0, 0, 4, 5, 6]]
iacob
  • 20,084
  • 6
  • 92
  • 119
jon
  • 33
  • 5

2 Answers2

1

Here is how to do it using SciPy:

from scipy.sparse import block_diag

block_diag((M1, M2, M3, M4))
Stanislas Morbieu
  • 1,721
  • 7
  • 11
1

Use PyTorch's torch.block_diag():

>>> torch.block_diag(M1,M2,M3,M4)

tensor([[1, 2, 0, 0, 0, 0, 0, 0],
        [2, 1, 0, 0, 0, 0, 0, 0],
        [0, 0, 1, 2, 0, 0, 0, 0],
        [0, 0, 0, 0, 3, 0, 0, 0],
        [0, 0, 0, 0, 0, 3, 4, 5],
        [0, 0, 0, 0, 0, 4, 5, 6]])
iacob
  • 20,084
  • 6
  • 92
  • 119