scipy block_diag of a list of matrices

雨燕双飞 提交于 2021-01-28 00:23:27

问题


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 = np.random.randint(-2, 2, (5,4))
sp.linalg.block_diag(x, y) # correct result

while if:

matrices = [x, y]
sp.linalg.block_diag(matrices) # wrong result. 

How can I solve this?


回答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]])



回答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!



来源:https://stackoverflow.com/questions/30895154/scipy-block-diag-of-a-list-of-matrices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!