问题
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