# 【线代&NumPy】第五章 – Vector课后练习 | 伴随矩阵求逆 | Cramer公式求联立方程 | 简述并提供代码

? 例1：

``````import numpy as np

def getMinorMatrix(A,i,j): # 删除矩阵A的i行和j列，并创建矩阵
n = len(A)
M = np.zeros((n-1, n-1))
for a in range(0,n-1):
k = a if (a < i) else a+1
for b in range(0, n-1):
l = b if (b < j) else b+1
M[a, b] = A[k, l]
return M

def determinant(M): # 计算
if len(M) == 2: # 2x2
return M[0,0]*M[1,1]-M[0,1]*M[1,0]

detVal = 0
for c in range(len(M)):
detVal += ((-1)**c)*M[0,c]*determinant(getMinorMatrix(M,0,c))
return detVal

A = np.array([[-4, 0, 2, -1, 0], [1, 3, -3, -1, 4], [2, 0, 1, 3, 0],
[-2, 1, -3, -1, 5], [1, -5, 1, 0, 5]])
print("A = ", A)
print("det(A) = ", determinant(A))
``````

? 运行结果：

A =  [[-4  0  2 -1  0]
[ 1  3 -3 -1  4]
[ 2  0  1  3  0]
[-2  1 -3 -1  5]
[ 1 -5  1  0  5]]
det(A) =  -997.0

? 例2：

``````import numpy as np

def cofactor(A, i, j): # 辅助因子
(n,m) = A.shape
M = np.zeros((n-1, m-1))
for a in range(0, n-1):
k = a if (a < i) else a+1
for b in range(0, m-1):
l = b if (b < j) else b+1
M[a,b] = A[k, l]

return (-1)**(i+j)*np.linalg.det(M)

detA = np.linalg.det(A) # A的矩阵式计算
(n,m) = A.shape

for i in range(0,n): # 生成伴随矩阵
for j in range(0, m):
if detA != 0.0:
else:
return 0

A = np.array([[-4, 0, 2, -1, 0], [1, 3, -3, -1, 4], [2, 0, 1, 3, 0],
[-2, 1, -3, -1, 5], [1, -5, 1, 0, 5]])
print("A = ", A)

print("A inverse = ", Ainv)``````

? 运行结果：

A =  [[-4  0  2 -1  0]
[ 1  3 -3 -1  4]
[ 2  0  1  3  0]
[-2  1 -3 -1  5]
[ 1 -5  1  0  5]]
A inverse =  [[-0.07321966  0.2106319  -0.03610832 -0.24573721  0.0772317 ]
[ 0.16950853  0.26579739  0.09729188 -0.14343029 -0.06920762]
[ 0.32397192  0.30090271  0.09127382 -0.35105316  0.11033099]
[-0.05917753 -0.24072217  0.32698094  0.28084253 -0.08826479]
[ 0.11935807  0.16349047  0.08625878 -0.02407222  0.09327984]]

``````import numpy as np

def solveByCramer(A, B): # # 利用Cramer公式求联立线性方程AX=B的解
X = np.zeros(len(B))
C = np.copy(A)
for i in range(0, len(B)):
for j in range(0, len(B)):
C[j,i] = B[j]
if i>0:
C[j,i-1] = A[j,i-1]
X[i] = np.linalg.det(C)/np.linalg.det(A)
return X

# AX = B의 해
A = np.array([[2,-1,5,1], [3,2,2,-6], [1,3,3,-1], [5,-2,-3,3]])
B = np.array([[-3], [-32], [-47], [49]])
X = solveByCramer(A, B)
print("A = ", A)
print("B = ", B)
print("X = ", X)``````

? 运行结果：

A =  [[ 2 -1  5  1]
[ 3  2  2 -6]
[ 1  3  3 -1]
[ 5 -2 -3  3]]
B =  [[ -3]
[-32]
[-47]
[ 49]]
X =  [  2. -12.  -4.   1.]

Introduction to Linear Algebra, International 4 th Edition by Gilbert Strang, Wellesley Cambridge Press.

THE END