class Matrix:
def __init__(self, matrix:list):
self.matrix = matrix
self.height = len(matrix)
self.width = len(matrix[0])
def __add__(self, other):
“””矩阵加法”””
result = []
for i1 in range(self.height):
result.append([])
for i2 in range(self.width):
result[i1].append(self.matrix[i1][i2] + other.matrix[i1][i2])
return Matrix(result)
def __sub__(self, other):
“””矩阵减法”””
result = []
for i1 in range(self.height):
result.append([])
for i2 in range(self.width):
result[i1].append(self.matrix[i1][i2] – other.matrix[i1][i2])
return Matrix(result)
def show_matrix(self):
“””输出矩阵”””
for i1 in range(self.height):
for i2 in range(self.width):
print(self.matrix[i1][i2], end=” “)
print()
def transpose(self):
“””矩阵转置”””
result = []
for i1 in range(self.width):
result.append([])
for i2 in range(self.height):
result[i1].append(self.matrix[i2][i1])
return Matrix(result)
def __mul__(self, other):
“””矩阵乘法”””
if isinstance(other, Matrix):
if self.width!= other.height:
raise ValueError(“Matrix dimensions are not compatible for multiplication.”)
else:
result = []
for i1 in range(self.height):
result.append([])
for i2 in range(other.width):
result[i1].append(0)
for i3 in range(self.width):
result[i1][i2] += self.matrix[i1][i3] * other.matrix[i3][i2]
return Matrix(result)
elif isinstance(other, (int, float)):
result = []
for i1 in range(self.height):
result.append([])
for i2 in range(self.width):
result[i1].append(self.matrix[i1][i2] * other)
return Matrix(result)
else:
raise ValueError(“Invalid operand type for multiplication.”)
def __rmul__(self, other):
“””矩阵乘法”””
if isinstance(other, Matrix):
if self.width!= other.height:
raise ValueError(“Matrix dimensions are not compatible for multiplication.”)
else:
result = []
for i1 in range(self.height):
result.append([])
for i2 in range(other.width):
result[i1].append(0)
for i3 in range(self.width):
result[i1][i2] += self.matrix[i1][i3] * other.matrix[i3][i2]
return Matrix(result)
elif isinstance(other, (int, float)):
result = []
for i1 in range(self.height):
result.append([])
for i2 in range(self.width):
result[i1].append(self.matrix[i1][i2] * other)
return Matrix(result)
else:
raise ValueError(“Invalid operand type for multiplication.”)
def __truediv__(self, other):
“””矩阵除法”””
if isinstance(other, (int, float)):
if other == 0:
raise ValueError(“Cannot divide by zero.”)
else:
result = []
for i1 in range(self.height):
result.append([])
for i2 in range(self.width):
result[i1].append(self.matrix[i1][i2] / other)
return Matrix(result)
else:
raise ValueError(“Invalid operand type for division.”)
def __getitem__(self, index):
“””获取矩阵中的元素”””
return self.matrix[index]
def __setitem__(self, index, value):
“””设置矩阵中的元素”””
self.matrix[index] = value
def __eq__(self, other):
“””判断两个矩阵是否相等”””
if isinstance(other, Matrix):
return self.matrix == other.matrix
else:
return False
def __ne__(self, other):
“””判断两个矩阵是否不相等”””
return not self.__eq__(other)
def __pow__(self, power:int):
“””矩阵幂”””
if not isinstance(power, int):
raise ValueError(“Power must be an integer.”)
if power < -1 or power == 0:
raise ValueError(“Power must be non-negative.”)
if power == -1:
return self.inverse_matrix()
result = Matrix(self.matrix)
for _ in range(power – 1):
result = result * self
return result
def __str__(self):
“””输出矩阵”””
result = “”
for i1 in range(self.height):
for i2 in range(self.width):
result += str(self.matrix[i1][i2]) + ” “
result += “\n”
return result
def determinant(self) -> float:
if self.height!= self.width:
raise ValueError(“The matrix must be square.”)
def permute(nums):
def backtrack(first=0):
if first == n:
output.append(nums[:])
for i in range(first, n):
nums[first], nums[i] = nums[i], nums[first]
backtrack(first + 1)
nums[first], nums[i] = nums[i], nums[first]
n = len(nums)
output = []
backtrack()
return output
def invers_order_number(array):
result = 0
for i1 in range(len(array)):
for i2 in range(i1 + 1, len(array)):
if array[i1] > array[i2]:
result += 1
return result
array = self.matrix
height = self.height
permutations = permute([i + 1 for i in range(height)])
result = 0
for perm in permutations:
product = 1
for i in range(height):
product *= array[i][perm[i] – 1]
result += product * (-1)**invers_order_number(perm)
return result
def inverse_matrix(self):
“””输出逆矩阵”””
try:
result_matrix = Matrix.__mul__(Matrix.adjoint_matrix(self), 1 / Matrix.determinant(self))
return result_matrix
except ZeroDivisionError:
return 0
def exchange_row(self, row1:int, row2:int):
“””交换矩阵的两行”””
# 不使用 deepcopy,创建一个新的矩阵
new_matrix = [row[:] for row in self.matrix]
# 交换两行
new_matrix[row1 – 1], new_matrix[row2 – 1] = new_matrix[row2 – 1], new_matrix[row1 – 1]
return Matrix(new_matrix)
def exchange_column(self, column1:int, column2:int):
“””交换矩阵的两列”””
# 不使用 deepcopy,创建一个新的矩阵
new_matrix = [row[:] for row in self.matrix]
# 交换两列
for i in range(len(new_matrix)):
new_matrix[i][column1 – 1], new_matrix[i][column2 – 1] = new_matrix[i][column2 – 1], new_matrix[i][column1 – 1]
return Matrix(new_matrix)
def adjoint_matrix(self):
“””输出方阵矩阵的伴随矩阵”””
def algebraic_cofactor(source_determinant:list, row:int, column:int) -> float:
“””计算行列式的代数余子式”””
# 不使用 deepcopy,创建一个新的矩阵
new_matrix = [row[:] for row in source_determinant]
# 删除指定的行和列
del new_matrix[row – 1]
for i in range(len(new_matrix)):
del new_matrix[i][column – 1]
# 计算新矩阵的行列式并返回代数余子式
return (-1) ** (row + column) * Matrix.determinant(Matrix(new_matrix))
result_matrix = [[0 for _ in range(self.width)] for _ in range(self.width)]
for i1 in range(self.width):
for i2 in range(self.width):
result_matrix[i2][i1] = algebraic_cofactor(self.matrix, i1 + 1, i2 + 1)
return Matrix(result_matrix)
def input_matrix(height:int, width:int):
“””输入矩阵”””
print(“Enter the elements of the matrix:”)
result = []
for i1 in range(height):
result.append([])
for i2 in range(width):
result[i1].append(eval(input(f”Enter the element at row {i1 + 1}, column {i2 + 1}: “)))
print(“—————finished—————-“)
return Matrix(result)
def main():
x = Matrix.input_matrix(4, 4)
print(x ** -1)
if __name__ == “__main__”:
main()
发表回复