Skip to content Skip to sidebar Skip to footer

Scipy Block_diag Of A List Of Matrices

How can I get a matrix which has as diagonal some matrices that I have in a list? I can get this if the matrices are not in a list for example: x = np.random.normal(0, 1, (3,2)) y

Solution 1:

import numpy as np
from scipy.linalg import block_diag

A = np.array([[1, 2], 
              [3, 4]])    
B = np.array([[5, 6], 
              [7, 8]])
C = [A,B]
block_diag(*C)
>>>array([[1, 2, 0, 0],
          [3, 4, 0, 0],
          [0, 0, 5, 6],
          [0, 0, 7, 8]])

Solution 2:

>>> import numpy as np
>>> from scipy.linalg import block_diag
>>> x = np.random.normal(0, 1, (3,2))
>>> y = np.random.randint(-2, 2, (5,4))
>>> test1 = block_diag(x, y)
>>> matrices = [x,y]
>>> test2 = block_diag(matrices[0],matrices[1])#Calling them separately inside block_diag
>>> print test1
[[ 0.25550034  0.07837795  0.          0.          0.          0.        ]
 [-1.29734655  0.13719009  0.          0.          0.          0.        ]
 [ 1.21197194 -0.17461216  0.          0.          0.          0.        ]
 [ 0.          0.         -1.          0.         -1.          1.        ]
 [ 0.          0.          0.         -1.         -1.          1.        ]
 [ 0.          0.         -1.         -1.         -2.         -1.        ]
 [ 0.          0.         -1.          1.          1.          0.        ]
 [ 0.          0.         -2.          0.         -2.          0.        ]]
>>> print test2
[[ 0.25550034  0.07837795  0.          0.          0.          0.        ]
 [-1.29734655  0.13719009  0.          0.          0.          0.        ]
 [ 1.21197194 -0.17461216  0.          0.          0.          0.        ]
 [ 0.          0.         -1.          0.         -1.          1.        ]
 [ 0.          0.          0.         -1.         -1.          1.        ]
 [ 0.          0.         -1.         -1.         -2.         -1.        ]
 [ 0.          0.         -1.          1.          1.          0.        ]
 [ 0.          0.         -2.          0.         -2.          0.        ]]
>>> test1.shape
(8, 6)
>>> test2.shape
(8, 6)
>>> 

So when we print, test1.shape, we get (8,6) and also the same for test2.shape. Calling them separately inside block_diag does the trick!


Post a Comment for "Scipy Block_diag Of A List Of Matrices"