线性代数与Python


(1)基础

安装
pip install numpy
引入
import numpy as np
创建矩阵
A = np.mat("0 1 2;1 0 3;4 -3 8")
A = np.mat([[1,14,20,1],[15,15,8,19],[0,18,5,20]])
B = np.array([[1,14,20,1],[15,15,8,19],[0,18,5,20]])
C = np.eye(3)        #三阶单位矩阵
D = np.diag([1,2,3]) #三阶对角矩阵
E = np.zeros((3,3))  #三阶零矩阵
求逆矩阵
A1 = np.linalg.inv(A)
矩阵的秩
b = np.linalg.matrix_rank(a)
矩阵的乘法
A = np.dot(A1, C)
矩阵的转置
b = a.T
矩阵A的行列式的值
A1 = np.linalg.det(A)
矩阵的特征值和特征向量
e,f = np.linalg.eig(C)
print("特征值:",e)
print("特征向量:",f)
伴随矩阵
Astar = np.linalg.inv(A)*np.linalg.det(A)

(2)可逆矩阵与逆运算

需要传递的明文信息为矩阵B,以矩阵A作为加密密钥,得到矩阵C,使用矩阵A的逆还原矩阵B

import numpy as np
B = np.array([[1,14,20,1],[15,15,8,19],[0,18,5,20]])
print("矩阵B:")
print(B)
A = np.array([[1,1,1],[-1,0,1],[0,1,1]])
print("矩阵A:")
print(A)
C = np.dot(A,B)
print("矩阵C:")
print(C)

print("矩阵A逆:")
A1 = np.linalg.inv(A)
print(A1)
B1 = np.dot(A1, C)
print("还原矩阵B:")
print(B1)
矩阵B:
[[ 1 14 20  1]
 [15 15  8 19]
 [ 0 18  5 20]]
矩阵A:
[[ 1  1  1]
 [-1  0  1]
 [ 0  1  1]]
矩阵C:
[[ 16  47  33  40]
 [ -1   4 -15  19]
 [ 15  33  13  39]]
矩阵A逆:
[[ 1.  0. -1.]
 [-1. -1.  2.]
 [ 1.  1. -1.]]
还原矩阵B:
[[ 1. 14. 20.  1.]
 [15. 15.  8. 19.]
 [ 0. 18.  5. 20.]]

https://www.runoob.com/numpy/numpy-linear-algebra.html