在python中求矩阵的辅矩阵

v1uwarro  于 2022-12-21  发布在  Python
关注(0)|答案(3)|浏览(135)

在解决用给出的余因子矩阵公式求矩阵的伴随矩阵的问题时,遇到了一些问题

c[i][j] = (-1)**(i+j)*m[i][j]

其中m表示矩阵行列式。

x = np.array([[1,3,5],[-2,-4,-5],[3,6,1]] , dtype = 'int')

我只能这样做,不知道如何继续,请帮助
为了找到余因子,我有这个提示def COF(C)创建一个空矩阵CO

for row
     for col
         sel_rows = all rows except current row 
         sel_columns = all cols except current col
         MATij = [selected rows and selected columns]
         compute COij
 return CO
nr9pn0ug

nr9pn0ug1#

import numpy as np
x = np.array([[1,3,5],[-2,-4,-5],[3,6,1]] , dtype = 'int')
m = np.linalg.det(x)
c =[[i for i in range(3)] for j in range(3)]
for i in range(3):
    for j in range(3):
        c[i][j] = (-1)*(i+j)*m
7y4bm7vi

7y4bm7vi2#

要使c.T工作时没有任何错误,数组c应该是一个numpy数组。这里@TaohidulIslam声明的数组c是一个Python列表。所以你会得到一个错误。
按如下方式声明cc =np.array([[i for i in range(3)] for j in range(3)])

ie3xauqp

ie3xauqp3#

你可以用下面适用于非奇异矩阵的方法通过转置余因子矩阵来计算伴随矩阵。首先,求出余因子矩阵,如下所示:https://www.geeksforgeeks.org/how-to-find-cofactor-of-a-matrix-using-numpy/然后,求余因子矩阵的转置。

import numpy as np
import math as mth

# get cofactors matrix 
def getcofat(x):
    eps = 1e-6
    detx = np.linalg.det(x)
    if (mth.fabs(detx) < eps):
        print("No possible to get cofactors for singular matrix with this method")
        x = None
        return x
    invx = np.linalg.pinv(x)
    invxT = invx.T
    x = invxT * detx
    return x
# get adj matrix
def getadj(x):
    eps = 1e-6
    detx = np.linalg.det(x)
    if (mth.fabs(detx) < eps):
        print("No possible to get adj matrix for singular matrix with this method")
        adjx = None
        return adjx
    cofatx = getcofat(x)
    adjx = cofatx.T
    return adjx

A = np.array([[1, 3, 5], [-2, -4, -5], [3, 6, 1]])
print(A)
print(np.linalg.det(A))
Acofat = getcofat(A)
print(Acofat)
Aadj = getadj(A)
print(Aadj)

相关问题