在SymPy中从块矩阵构建矩阵

时间:2018-05-30 14:01:04

标签: python matrix sympy

我想要一个矩阵看起来像这样:

import sympy as sp
sp.Matrix([[1,0,2,0],[0,1,0,2],[1,0,2,0],[0,1,0,2]])
# output
#⎡1  0  2  0⎤
#⎢          ⎥
#⎢0  1  0  2⎥
#⎢          ⎥
#⎢1  0  2  0⎥
#⎢          ⎥
#⎣0  1  0  2⎦

我想从块矩阵构造一个新矩阵:

s=sp.eye(2)
sp.Matrix([[s,2*s],[s,2*s]])
# output:
#⎡⎡1  0⎤  ⎡2  0⎤⎤
#⎢⎢    ⎥  ⎢    ⎥⎥
#⎢⎣0  1⎦  ⎣0  2⎦⎥
#⎢              ⎥
#⎢⎡1  0⎤  ⎡2  0⎤⎥
#⎢⎢    ⎥  ⎢    ⎥⎥
#⎣⎣0  1⎦  ⎣0  2⎦⎦

输出内部有额外的括号。

一种解决方案是sympy.functions.transpose方法:

from sympy.functions import transpose
sp.Matrix([transpose(sp.Matrix([s*i for i in range(1,3)])) for j in range(1,3)])
# output 
#⎡1  0  2  0⎤
#⎢          ⎥
#⎢0  1  0  2⎥
#⎢          ⎥
#⎢1  0  2  0⎥
#⎢          ⎥
#⎣0  1  0  2⎦

这个解决方案相当繁琐。我想知道是否有更好的解决方案?

简而言之,sp.Matrix方法似乎只是组合矩阵,只要它们在一维列表中即可。

2 个答案:

答案 0 :(得分:2)

使用TensorProduct

>>> from sympy import *
>>> from sympy.physics.quantum import TensorProduct
>>> A = ones(2,1) * Matrix([1,2]).T
>>> A
Matrix([
[1, 2],
[1, 2]])
>>> TensorProduct(A, eye(2))
Matrix([
[1, 0, 2, 0],
[0, 1, 0, 2],
[1, 0, 2, 0],
[0, 1, 0, 2]])

使用BlockMatrix

>>> from sympy import *
>>> BlockMatrix([[eye(2), 2*eye(2)],[eye(2), 2*eye(2)]])
Matrix([
[Matrix([
[1, 0],
[0, 1]]), Matrix([
[2, 0],
[0, 2]])],
[Matrix([
[1, 0],
[0, 1]]), Matrix([
[2, 0],
[0, 2]])]])
>>> Matrix(BlockMatrix([[eye(2), 2*eye(2)],[eye(2), 2*eye(2)]]))
Matrix([
[1, 0, 2, 0],
[0, 1, 0, 2],
[1, 0, 2, 0],
[0, 1, 0, 2]])

答案 1 :(得分:1)

您还可以使用 hstackvstack 函数:

A = eye(2)
B = 2 * eye(2)
Matrix.vstack(
    Matrix.hstack(A, B),
    Matrix.hstack(A, B)
)
相关问题