gpt4 book ai didi

python - 在 SymPy 中从分块矩阵构建矩阵

转载 作者:太空宇宙 更新时间:2023-11-04 00:16:51 25 4
gpt4 key购买 nike

我想要一个像这样的矩阵:

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⎦

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

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 方法似乎可以组合矩阵,只要它们位于一维列表中。

最佳答案

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

关于python - 在 SymPy 中从分块矩阵构建矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50606675/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com