我在解决通过给定辅因子矩阵公式求矩阵共轭的问题时遇到一些问题
c[i][j] = (-1)**(i+j)*m[i][j]
其中 m 代表矩阵的行列式。
x = np.array([[1,3,5],[-2,-4,-5],[3,6,1]] , dtype = 'int')
我只能做到这一点,不知道如何继续,请帮忙
为了找到辅因子,我有这个提示 定义 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
我们可以使用布尔索引来获取子矩阵。还可以通过变量
sgn_row
和 sgn_col
分别跟踪行列式和列行列式所需的符号变化。
def cofactor(A):
"""
Calculate cofactor matrix of A
"""
sel_rows = np.ones(A.shape[0],dtype=bool)
sel_columns = np.ones(A.shape[1],dtype=bool)
CO = np.zeros_like(A)
sgn_row = 1
for row in range(A.shape[0]):
# Unselect current row
sel_rows[row] = False
sgn_col = 1
for col in range(A.shape[1]):
# Unselect current column
sel_columns[col] = False
# Extract submatrix
MATij = A[sel_rows][:,sel_columns]
CO[row,col] = sgn_row*sgn_col*np.linalg.det(MATij)
# Reselect current column
sel_columns[col] = True
sgn_col = -sgn_col
sel_rows[row] = True
# Reselect current row
sgn_row = -sgn_row
return CO
def adjugate(A):
"""
Calculate adjugate matrix of A
"""
return cofactor(A).T
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
要使
c.T
正常工作,数组 c
应该是一个 numpy 数组。这里 @TaohidulIslam 声明的数组 c
是一个 Python 列表。所以你会得到一个错误。
声明
c
如下:
c =np.array([[i for i in range(3)] for j in range(3)])
可以通过辅因子矩阵的转置来计算辅助矩阵 下面的方法适用于非奇异矩阵。 首先求出辅因子矩阵,如下: 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)
不幸的是,我还没有评论的声誉,但在我看来,@syockit 的代码有问题。对于矩阵 A=np.array([[-3,1,2],[3,-2,1],[0,1,-3]]),cofactor(A) 返回 np.array([[ 5,9,3],[4,9,3],[5,9,3]]),而我相信所有行都应该是 [5,9,3]。