python:不使用numpy创建逆矩阵

2admgd59  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(768)

我用的是pyomo,需要一个函数,可以给出平方矩阵的逆矩阵,而不用numpy。我已联机找到一个函数,但找不到导致以下错误消息的问题:
操作数无法与形状(0,4)(3,4)一起广播

def transposeMatrix(m):
    return list(map(list,zip(*m)))

def getMatrixMinor(m,i,j):
    return [row[:j] + row[j+1:] for row in (m[:i]+m[i+1:])]

def getMatrixDeternminant(m):
    #base case for 2x2 matrix
    if len(m) == 2:
        return m[0][0]*m[1][1]-m[0][1]*m[1][0]

    determinant = 0
    for c in range(len(m)):
        determinant += ((-1)**c)*m[0][c]*getMatrixDeternminant(getMatrixMinor(m,0,c))
    return determinant

def getMatrixInverse(m):
    determinant = getMatrixDeternminant(m)
    #special case for 2x2 matrix:
    if len(m) == 2:
        return [[m[1][1]/determinant, -1*m[0][1]/determinant],
                [-1*m[1][0]/determinant, m[0][0]/determinant]]

    #find matrix of cofactors
    cofactors = []
    for r in range(len(m)):
        cofactorRow = []
        for c in range(len(m)):
            minor = getMatrixMinor(m,r,c)
            cofactorRow.append(((-1)**(r+c)) * getMatrixDeternminant(minor))
        cofactors.append(cofactorRow)
    cofactors = transposeMatrix(cofactors)
    for r in range(len(cofactors)):
        for c in range(len(cofactors)):
            cofactors[r][c] = cofactors[r][c]/determinant
    return cofactors

a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [10, 4, 6, 2]])
getMatrixInverse(a)
ki0zmccv

ki0zmccv1#

如果我们去掉numpy引用,只使用

a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [10, 4, 6, 2]]

然后代码就工作了。但是,您的示例有一个零行列式,因此在计算逆矩阵时,您将得到一个零除误差。如果你使用一个矩阵,比如

a = [[ 0., 2.0, 3.0, 4.0 ], [ 5.0, 6.0, 7.0, 8. ],[ 9.0, 10.0, 11.0, 12.0 ], [ 13.,14.,15., 0. ]]

它的行列式是-64,那么你就得到了正确的倒数

[[-1.0, 2.0, -1.0, 0.0], [2.0, -6.8125, 3.875, -0.0625], [-1.0, 4.625, -2.75, 0.125], [0.0, -0.0625, 0.125, -0.0625]]

相关问题