import numpy as np
class Matrix:
def __init__(self, data):
self.data = data
self.shape = (len(data), len(data[0]))
def __add__(self, other):
# 矩阵加法
if self.shape != other.shape:
raise ValueError("矩阵形状不匹配")
res_data = [[0] * self.shape[1] for i in range(self.shape[0])]
for i in range(self.shape[0]):
for j in range(self.shape[1]):
res_data[i][j] = self.data[i][j] + other.data[i][j]
return Matrix(res_data)
def __sub__(self, other):
# 矩阵减法
if self.shape != other.shape:
raise ValueError("矩阵形状不匹配")
res_data = [[0] * self.shape[1] for i in range(self.shape[0])]
for i in range(self.shape[0]):
for j in range(self.shape[1]):
res_data[i][j] = self.data[i][j] - other.data[i][j]
return Matrix(res_data)
def __mul__(self, other):
# 矩阵乘法
if self.shape[1] != other.shape[0]:
raise ValueError("矩阵形状不匹配")
other_data = np.array(other.data)
res_data = [[0] * other.shape[1] for i in range(self.shape[0])]
for i in range(self.shape[0]):
for j in range(other.shape[1]):
res_data[i][j] = np.dot(self.data[i], other_data[:, j])
return Matrix(res_data)
def __rmul__(self, scalar):
# 矩阵与标量相乘
res_data = [[0] * self.shape[1] for i in range(self.shape[0])]
for i in range(self.shape[0]):
for j in range(self.shape[1]):
res_data[i][j] = scalar * self.data[i][j]
return Matrix(res_data)
def __truediv__(self, scalar):
# 矩阵除以标量
res_data = [[0] * self.shape[1] for i in range(self.shape[0])]
for i in range(self.shape[0]):
for j in range(self.shape[1]):
res_data[i][j] = self.data[i][j] / scalar
return Matrix(res_data)
def __str__(self):
# 以矩阵形式输出
return str(self.data)
def transpose(self):
# 矩阵转置
res_data = [[0] * self.shape[0] for i in range(self.shape[1])]
for i in range(self.shape[1]):
for j in range(self.shape[0]):
res_data[i][j] = self.data[j][i]
return Matrix(res_data)
def det(self):
# 计算矩阵行列式
if self.shape[0] != self.shape[1]:
raise ValueError("矩阵不是方阵")
return np.linalg.det(self.data)
def trace(self):
# 计算矩阵迹
if self.shape[0] != self.shape[1]:
raise ValueError("矩阵不是方阵")
return np.trace(self.data)
def eigen(self):
# 计算矩阵特征值和特征向量
if self.shape[0] != self.shape[1]:
raise ValueError("矩阵不是方阵")
eigen_values, eigen_vectors = np.linalg.eig(self.data)
return eigen_values, eigen_vectors
if __name__ == "__main__":
mat1 = Matrix([[1, 2], [3, 4]])
mat2 = Matrix([[5, 6], [7, 8]])
print(mat1 + mat2) # 输出矩阵mat1和mat2的和
print(mat1 - mat2) # 输出矩阵mat1和mat2的差
print(mat1 * mat2) # 输出矩阵mat1和mat2的乘积
print(3 * mat1) # 输出标量与矩阵mat1的积
print(mat1.transpose()) # 输出矩阵mat1的转置
print(mat1.det()) # 输出矩阵mat1的行列式
print(mat1.trace()) # 输出矩阵mat1的迹
print(mat1.eigen()) # 输出矩阵mat1的特征值和特征向量
标签:__,res,self,矩阵,shape,计算,data From: https://www.cnblogs.com/yunbianshangdadun/p/17499245.html