将3D numpy数组转换成块对角矩阵 [英] 3D numpy array into block diagonal matrix

查看:123
本文介绍了将3D numpy数组转换成块对角矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种将nXaXb numpy数组转换为块对角矩阵的方法。我已经碰到过 scipy.linalg。 block_diag ,其缺点(对于我而言)是要求矩阵的每个块分别给出。但是,这在n很高时很有挑战性,因此要使情况更清楚,可以说我有

I am looking for a way to convert a nXaXb numpy array into a block diagonal matrix. 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. However, this is challenging when n is very high, so to make things more clear lets say I have a

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

我要实现的目标与

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

这实际上是一个示例,其中a具有数百个元素。

This is just as an example in actual case a has hundreds of elements.

推荐答案

尝试使用 block_diag(* a)。参见下面的示例:

Try using 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)

这篇关于将3D numpy数组转换成块对角矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆