参考文献 矩阵求解行列式 python实现求矩阵行列式、求逆矩阵等各种矩阵操作(不使用numpy包)
矩阵乘法
矩阵乘法中,需要判断两个矩阵是否可以进行相乘,即前一个矩阵的列是否等于后一个矩阵的行。具体代码如下:
class Solution:
def multiplyofmatrix(self, A, f):
"""
Compute matrix A * matrix f.
For example:
Input:
A: [[1, 2], [3, 4]] Row of A: 2 Col of A: 2
f: [[1, 2], [3, 4]] Row of f: 2 Col of f: 2
Output:
ans: [[7, 10], [15, 22]]
s.t. A.col == f.col
"""
Arow, Acol = len(A), len(A[0])
frow, fcol = len(f), len(f[0])
if Acol != frow:
return 'False!'
ans = [[0] * fcol for _ in range(Arow)]
for i in range(fcol):
for j in range(Arow):
for k in range(frow):
ans[j][i] += A[j][k]*f[k][i]
return ans
if __name__=='__main__':
a = Solution().multiplyofmatrix([[1, 2], [3, 4]], [[1, 2], [3, 4]])
print(a)
转置矩阵
def transposeofmatrix(A):
"""
Matrix transpose.
For example:
Input:
A = [[1, 2],
[3, 4]]
Output:
A_transpose = [[1, 3],
[2, 4]]
"""
return [list(raw) for raw in zip(*A)]
矩阵余矩阵
def submatrix(A, i, j):
m, n = len(A), len(A[0])
C = [[A[x][y] for y in range(n) if y != j] for x in range(m) if x != i]
return C
矩阵行列式
需要用到矩阵余矩阵函数,代码如下:
def detofmatrix(A):
m = len(A)
n = len(A[0])
if (m == 1 and n == 1):
return A[0][0]
else:
value = 0
for j in range(n):
value += ((-1) ** (j + 2)) * A[0][j] * detofmatrix(submatrix(A, 0, j))
return value
矩阵的逆
需要用到矩阵行列式函数和余矩阵函数,代码如下:
def inverseofmatrix(A):
m = len(A)
n = len(A[0])
C = [[0] * n for _ in range(m)]
d = self.detofmatrix(A)
for i in range(m):
for j in range(n):
C[i][j] = ((-1) ** (i + j + 2)) * detofmatrix(submatrix(A, j, i))
C[i][j] = C[i][j] / d
return C
求方程组根
求
∣
A
x
?
b
∣
=
0
|Ax - b| = 0
∣Ax?b∣=0即为求
x
=
A
?
1
?
b
x = A^{-1} * b
x=A?1?b(A可逆的情况下),调用求逆函数和矩阵相乘函数即可。
求一元n次方程正实数根
例如:
x
3
+
a
x
2
+
b
x
=
c
x^3+ax^2+bx=c
x3+ax2+bx=c,其中a, b, c, 均为正整数,求正实数根。
---------持续更新----------
|