# 3. 矩阵求逆代码(python)

## 3.1 利用伴随矩阵

def _determinant(matrix):
"""递归计算矩阵行列式"""
if len(matrix) == 1:
return matrix[0][0]
else:
d = 0
matrix_row, matrix_col = len(matrix), len(matrix[0])
for col in range(matrix_col):
# 删去第 0 行 col 列
m = [[matrix[i][j] for j in range(matrix_col) if j != col] for i in range(matrix_row) if i != 0]
d = d + (-1) ** (col & 1) * matrix[0][col] * _determinant(m)
return d

def _cofactor(matrix):
"""计算伴随矩阵"""
matrix_row, matrix_col = len(matrix), len(matrix[0])
res = [[0 for _ in range(matrix_col)] for _ in range(matrix_row)]

for row in range(matrix_row):
for col in range(matrix_col):
# 删去第 i 行 j 列
m = [[matrix[i][j] for j in range(matrix_col) if j != col] for i in range(matrix_row) if i != row]
# 计算余子式
res[row][col] = (-1) ** ((row + col) & 1) * _determinant(m)
return res

def _traverse(matrix):
"""矩阵转置"""
return [[matrix[col][row] for col in range(len(matrix[0]))] for row in range(len(matrix))]

def inverse(matrix):
d = _determinant(matrix)  # 行列式
if d == 0:  # 行列式等于0，不存在逆矩阵
return None
else:
cofactor = _cofactor(matrix)  # 获取伴随矩阵
res = _traverse(cofactor)  # 伴随矩阵的转置
# 将每个元素都除以 d
for row in range(len(res)):
for col in range(len(res[0])):
res[row][col] = res[row][col] / d
return res


## 3.2 利用高斯行变换

def inverse(matrix):
row, col = len(matrix), len(matrix[0])  # 矩阵的行列
t_matrix = [[matrix[r][c] for c in range(col)] for r in range(row)]
e_matrix = [[0 if c != r else 1 for c in range(col)] for r in range(row)]  # 扩展矩阵

for i in range(row):
# 寻找第i列不为0的行
for r in range(i, row):
if t_matrix[r][i] != 0:
if i != r:
t_matrix[i], t_matrix[r] = t_matrix[r], t_matrix[i]
e_matrix[i], e_matrix[r] = e_matrix[r], e_matrix[i]
break
else:  # 找不到对应的行，没有逆矩阵
return None

# 对当前行的变换
temp = t_matrix[i][i]
for c in range(col):
t_matrix[i][c] /= temp
e_matrix[i][c] /= temp
# 对其它行的变换
for r in range(row):
if r != i:
temp = t_matrix[r][i]
for c in range(col):
e_matrix[r][c] = e_matrix[r][c] - e_matrix[i][c] * temp
t_matrix[r][c] = t_matrix[r][c] - t_matrix[i][c] * temp
return e_matrix


# 4. 最后

m = [[7, 18, 16, 9, 13],
[21, 0, 21, 1, 22],
[1, 20, 11, 2, 17],
[1, 0, 14, 20, 5],
[10, 13, 11, 22, 5]]


posted @ 2021-07-15 11:48  kentle  阅读(1150)  评论(2编辑  收藏  举报