如何将块转换为块对角矩阵(NumPy) [英] How can I transform blocks into a blockdiagonal matrix (NumPy)

查看:630
本文介绍了如何将块转换为块对角矩阵(NumPy)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在NumPy中,我有三个相同大小的正方形矩阵.我想将它们组合成块对角矩阵.

I have three same-size square matrices in NumPy. I would like to combine these to a block-diagonal matrix.

示例:

a1 = np.array([[1,1,1],[1,1,1],[1,1,1]])
a2 = np.array([[2,2,2],[2,2,2],[2,2,2]])
a3 = np.array([[3,3,3],[3,3,3],[3,3,3]])

r = np.array([[1,1,1,0,0,0,0,0,0],[1,1,1,0,0,0,0,0,0],[1,1,1,0,0,0,0,0,0],[0,0,0,2,2,2,0,0,0],[0,0,0,2,2,2,0,0,0],[0,0,0,2,2,2,0,0,0],[0,0,0,0,0,0,3,3,3],[0,0,0,0,0,0,3,3,3],[0,0,0,0,0,0,3,3,3]])

做到这一点的最佳方法是什么?

What is the best way to do this?

推荐答案

scipy.linalg具有block_diag函数以自动执行此操作

scipy.linalg has a block_diag function to do this automatically

>>> a1 = np.array([[1,1,1],[1,1,1],[1,1,1]])
>>> a2 = np.array([[2,2,2],[2,2,2],[2,2,2]])
>>> a3 = np.array([[3,3,3],[3,3,3],[3,3,3]])
>>> import scipy.linalg
>>> scipy.linalg.block_diag(a1, a2, a3)
array([[1, 1, 1, 0, 0, 0, 0, 0, 0],
       [1, 1, 1, 0, 0, 0, 0, 0, 0],
       [1, 1, 1, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 2, 2, 2, 0, 0, 0],
       [0, 0, 0, 2, 2, 2, 0, 0, 0],
       [0, 0, 0, 2, 2, 2, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 3, 3, 3],
       [0, 0, 0, 0, 0, 0, 3, 3, 3],
       [0, 0, 0, 0, 0, 0, 3, 3, 3]])
>>> r = np.array([[1,1,1,0,0,0,0,0,0],[1,1,1,0,0,0,0,0,0],[1,1,1,0,0,0,0,0,0], [0,0,0,2,2,2,0,0,0],[0,0,0,2,2,2,0,0,0],[0,0,0,2,2,2,0,0,0],[0,0,0,0,0,0,3,3,3],[0,0,0,0,0,0,3,3,3],[0,0,0,0,0,0,3,3,3]])
>>> (scipy.linalg.block_diag(a1, a2, a3)  == r).all()
True

这篇关于如何将块转换为块对角矩阵(NumPy)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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