1、创建矩阵
import numpy as np
#2行3列
matrix1 = np.array([[1, 2, 3], [4, 5, 6]])
#3行2列
matrix2 = np.array([[7, 8], [9, 10], [11, 12]])
2、矩阵的相加
matrix1 = np.array([[1, 2, 3], [4, 5, 6]])
matrix2 = np.array([[7, 8, 9], [10, 11, 12]])
result = np.add(matrix1, matrix2)
3、矩阵的点乘
import numpy as np
matrix1 = np.array([[1, 2, 3], [4, 5, 6]])
matrix2 = np.array([[7, 8], [9, 10], [11, 12]])
result = matrix1 * matrix2
print(result)
4、矩阵的转置
# Create a matrix
matrix = np.array([[1, 2, 3], [4, 5, 6]])
# Transpose the matrix,创建矩阵的视图,而不是新矩阵
result = np.transpose(matrix)
print(result)
#如果想将转置的矩阵保存,使用copy()方法,保存在result中。
# Create a matrix
matrix = np.array([[1, 2, 3], [4, 5, 6]])
# Transpose the matrix and create a new matrix
result = np.transpose(matrix).copy()
5、求方阵的行列式的值(浮点运算):
import numpy as np
# Create a matrix
matrix = np.array([[1, 2], [3, 4]])
# 计算方阵对应的行列式
result = np.linalg.det(matrix)
# 这一步由于浮点运算会产生近似值,使用round来取整
rounded_result = round(result)
print(rounded_result)
6、求方阵的逆矩阵:
matrix = np.array([[1, 2], [3, 4]])
# Calculate the inverse of the matrix
result = np.linalg.inv(matrix)
print(result)
7、求矩阵的伴随矩阵:
import numpy as np
# Create a matrix
matrix = np.array([[1, 2], [3, 4]])
# 方阵的行列式
det = np.linalg.det(matrix)
# 方阵的逆矩阵
inv = np.linalg.inv(matrix)
# 矩阵的伴随=行列式*它的逆矩阵
adj = det * inv
print(adj)
8、求矩阵的秩:
# Create a matrix
matrix = np.array([[1, 2, 3], [2, 4, 6], [3, 6, 9]])
# Calculate the rank of the matrix
rank = np.linalg.matrix_rank(matrix)
print(rank)
9、求矩阵的特征值和特征向量:
import numpy as np
# Create a matrix
matrix = np.array([[-1,1,0], [-4,3,0], [1,0,2]])
eigenvalues, eigenvectors = np.linalg.eig(matrix)
print(eigenvalues)
print(eigenvectors)
输出:
特征值为2,1,1,对应的特征向量为:k1(0,0,1),k2(1,2,-1),k2(1,2,-1)。
该文介绍了如何使用NumPy库进行矩阵创建、相加、点乘、转置、求行列式、逆矩阵、伴随矩阵、秩以及特征值和特征向量的计算,展示了Python在数值计算中的应用。


被折叠的 条评论
为什么被折叠?



