简体   繁体   English

3D numpy数组成块对角矩阵

[英]3D numpy array into block diagonal matrix

I am looking for a way to convert a nXaXb numpy array into a block diagonal matrix. 我正在寻找一种方法将nXaXb numpy数组转换为块对角矩阵。 I have already came across scipy.linalg.block_diag , the down side of which (for my case) is it requires each blocks of the matrix to be given separately. 我已经遇到过scipy.linalg.block_diag ,其中的下方(对于我的情况)是它需要单独给出矩阵的每个块。 However, this is challenging when n is very high, so to make things more clear lets say I have a 然而,当n非常高时,这是具有挑战性的,所以为了使事情更清楚,可以说我有一个

import numpy as np    
a = np.random.rand(3,2,2)
array([[[ 0.33599705,  0.92803544],
        [ 0.6087729 ,  0.8557143 ]],
       [[ 0.81496749,  0.15694689],
        [ 0.87476697,  0.67761456]],
       [[ 0.11375185,  0.32927167],
        [ 0.3456032 ,  0.48672131]]])

what I want to achieve is something the same as 我想要实现的是同样的东西

from scipy.linalg import block_diag
block_diag(a[0], a[1],a[2])
array([[ 0.33599705,  0.92803544,  0.        ,  0.        ,  0.        ,   0.        ],
       [ 0.6087729 ,  0.8557143 ,  0.        ,  0.        ,  0.        ,   0.        ],
       [ 0.        ,  0.        ,  0.81496749,  0.15694689,  0.        ,   0.        ],
       [ 0.        ,  0.        ,  0.87476697,  0.67761456,  0.        ,   0.        ],
       [ 0.        ,  0.        ,  0.        ,  0.        ,  0.11375185,   0.32927167],
       [ 0.        ,  0.        ,  0.        ,  0.        ,  0.3456032 ,   0.48672131]])

This is just as an example in actual case a has hundreds of elements. 这仅仅是在实际情况中具有数百个元素的示例。

Try using block_diag(*a) . 尝试使用block_diag(*a) See example below: 见下面的例子:

In [9]: paste
import numpy as np
a = np.random.rand(3,2,2)
from scipy.linalg import block_diag
b = block_diag(a[0], a[1],a[2])

c = block_diag(*a)
b == c

## -- End pasted text --
Out[9]:
array([[ True,  True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True,  True]], dtype=bool)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM