从子矩阵列表在 sympy 中构建矩阵

时间:2021-04-23 14:35:45

标签: python matrix sympy

我正在使用 sympy(python 模块)并且我试图从列表中声明一个矩阵,但我需要一种特定的方式来声明它,因为我知道的那个不适合我的问题。

我有一个这样的数组 listm = [2,0,0,2,0,0,0,0,2,0,0,2,0,0,0,0] 并且我想声明一个 Matrix 对象,使得 4 个数字的每个子集(但通常我想为每个 n x n 矩阵实现这个)是一个子矩阵。我的意思是,结果一定是这样的:

[2,0,0,0]
[0,2,0,0]
[2,0,0,0]
[0,2,0,0]

如果我以通常的方式声明mat = Matrix(4,4,listm),我会得到

[2,0,0,2]
[0,0,0,0]
[2,0,0,2]
[0,0,0,0]

预先感谢您的帮助

2 个答案:

答案 0 :(得分:0)

我对 sympy 矩阵代码不够熟悉。但使用 numpy 相对容易。

isympy 会话中:

In [2]: listm = [2,0,0,2,0,0,0,0,2,0,0,2,0,0,0,0]
In [3]: import numpy as np
In [4]: arr = np.array(listm)
In [5]: arr
Out[5]: array([2, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 2, 0, 0, 0, 0])
In [6]: arr.reshape(4,4)
Out[6]: 
array([[2, 0, 0, 2],
       [0, 0, 0, 0],
       [2, 0, 0, 2],
       [0, 0, 0, 0]])
In [7]: arr.reshape(2,2,2,2)
Out[7]: 
array([[[[2, 0],
         [0, 2]],

        [[0, 0],
         [0, 0]]],


       [[[2, 0],
         [0, 2]],

        [[0, 0],
         [0, 0]]]])
In [8]: arr.reshape(2,2,2,2).transpose(0,2,1,3).reshape(4,4)
Out[8]: 
array([[2, 0, 0, 0],
       [0, 2, 0, 0],
       [2, 0, 0, 0],
       [0, 2, 0, 0]])

并从中制作sympy.Matrix

In [9]: Matrix(_)
Out[9]: 
⎡2  0  0  0⎤
⎢          ⎥
⎢0  2  0  0⎥
⎢          ⎥
⎢2  0  0  0⎥
⎢          ⎥
⎣0  2  0  0⎦

答案 1 :(得分:0)

BlockMatrix 可以用 Matrix 元素实例化。因此,SymPy 中的技巧是将您的列表(称为 L)放入具有您所描述语义的矩阵列表中。假设你想要一个 nxn 元素的 2x2 矩阵,我会做这样的事情(显示 n = 3 的情况:

>>> from sympy import BlockMatrix, Matrix
>>> from sympy.utilities.iterables import reshape
>>> n = 3
... L = [i for i in range(4*n**2)]
... m = [Matrix(n,n,i) for i in reshape(L, [n**2])]
... M = reshape(m, [2])
... Matrix(BlockMatrix(M))
... 
Matrix([
[ 0,  1,  2,  9, 10, 11],
[ 3,  4,  5, 12, 13, 14],
[ 6,  7,  8, 15, 16, 17],
[18, 19, 20, 27, 28, 29],
[21, 22, 23, 30, 31, 32],
[24, 25, 26, 33, 34, 35]])