从 SymPy 中的块矩阵构建矩阵

Xia*_*Liu 5 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?
Run Code Online (Sandbox Code Playgroud)

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

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??
Run Code Online (Sandbox Code Playgroud)

输出里面有额外的括号。

一种解决方案是通过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?
Run Code Online (Sandbox Code Playgroud)

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

简而言之,该sp.Matrix方法似乎只是将矩阵组合在一维列表中。

Rod*_*edo 5

使用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]])
Run Code Online (Sandbox Code Playgroud)

使用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]])
Run Code Online (Sandbox Code Playgroud)

  • 我更喜欢第二个,因为一些块矩阵不能由 `TensorProduct` 构造。 (2认同)