SymPy 中矩阵的逆?

问题描述 投票:0回答:3

我想知道如何创建一个矩阵并使用 Python 中的 SymPy 计算其逆矩阵?

例如,对于这个符号矩阵:

python matrix sympy
3个回答
22
投票

如果你的问题是:如何在 sympy 中计算矩阵 M 的逆矩阵:

M_inverse = M.inv()

至于如何创建矩阵:

M = Matrix(2,3, [1,2,3,4,5,6])

将为您提供以下 2X3 矩阵:

1 2 3

4 5 6

参见:http://docs.sympy.org/0.7.2/modules/matrices/matrices.html


13
投票

这是我们如何计算 symbolic 矩阵的逆矩阵的示例(从问题中获取):

import sympy as sym


# Not necessary but gives nice-looking latex output
# More info at: http://docs.sympy.org/latest/tutorial/printing.html
sym.init_printing()

sx, sy, rho = sym.symbols('sigma_x sigma_y rho')
matrix = sym.Matrix([[sx ** 2, rho * sx * sy], 
                     [rho * sx * sy, sy ** 2]])

现在打印逆

matrix.inv()
将给出:

可以进一步简化,如

sym.simplify(matrix.inv())


0
投票

可用的 sympy 方法对于符号矩阵来说非常慢。 输入操作速度更快。我在这篇论文中以“部分反转”的名称找到了它:doi.org/10.1088/1402-4896/ad298a.

这是维度为 (2,2) 和 (3,3) 的符号矩阵的代码和时间性能图。 (.inv() 方法无法为我完成更高维度的编译,而“部分反转”则相当快地完成这项工作。)

from sympy import Matrix, Symbol, simplify

def sp_partial_inversion(m, *cells):
    ''' Partial inversion algorithm.
    ARGUMENTS
        m <sympy.Matrix> : symbolic matrix
        *cells <tuple>   : 2-tuples with matrix indices to perform partial inversion on.
    RETURNS
        <sympy.Matrix>   : matrix m partially-inverted at indices *cells
    '''
    # Partial inversion algorithm
    M = m.copy()
    for cell in cells:
        i,k = cell
        z = M[i,k]
        newmat = []
        for r in range(m.shape[0]):
            newrow = []
            for c in range(m.shape[1]):
                if i == r:
                    if k == c:  # Pivot cell
                        newrow.append( 1/z )
                    else:       # Pivot row
                        newrow.append( -M[r,c]/z )
                else:
                    if k == c:  # Pivot col
                        newrow.append( M[r,c]/z )
                    else:       # Elsewhere
                        newrow.append( M[r,c] - M[i,c]*M[r,k]/z )
            newmat.append(newrow)
        M =  Matrix(newmat)
    #
    return M

def SymbolicMatrix(n):
    "Generates symbolic matrix for tests"
    return Matrix( [ Symbol( f'm_{i}' ) for i in range(n**2) ] ).reshape(n,n)

def FullInversion(m):
    "Full matrix inversion is partial inversion at all i==j."
    cells = [(i,i) for i in range(m.shape[0])]
    return sp_partial_inversion(m, *cells)

# Test 1 --- Z should be matrix of zeros
M = SymbolicMatrix(3)
#Z = simplify( FullInversion(M) - M.inv() )

# Test 2 ---
M = SymbolicMatrix(4)
M_ = simplify( FullInversion(M) )
M_

检查绘图:

Figure of time performance plot for 1000 sympy symbolic matrices from (2,2) to (3,3).

Figure of time performance plot for 100 sympy symbolic matrices from (2,2) to (4,4).

它也可以用于数值矩阵,但在我的测试中它并不比 numpy 的默认矩阵求逆更快。

© www.soinside.com 2019 - 2024. All rights reserved.