定义3*3矩阵类Matrix,在其中重载运算符“+” “-” “*”实现矩阵的基本运算
时间: 2025-07-06 08:57:31 浏览: 4
在定义一个3x3矩阵类`Matrix`,首先我们需要考虑包含三个二维数组来表示矩阵的行和列,以及一些基本属性如元素值、维度等。为了能重载运算符`+`(加法)、`-`(减法)和`*`(乘法),我们需要覆盖这些操作符的函数,让它们能够对矩阵元素进行对应位置的加减乘计算。
以下是一个简单的Python示例:
```python
class Matrix3x3:
def __init__(self, elements):
self.rows = [list(row) for row in elements]
def __add__(self, other):
if isinstance(other, Matrix3x3) and len(self.rows) == len(other.rows) and len(self.rows[0]) == len(other.rows[0]):
result = [[self[i][j] + other[i][j] for j in range(len(self.rows[0]))] for i in range(len(self.rows))]
return Matrix3x3(result)
else:
raise ValueError("Cannot add matrices of different dimensions")
def __sub__(self, other):
# 类似于__add__方法,只需将加法变为减法即可
if isinstance(other, Matrix3x3) and ...:
return Matrix3x3([self[i][j] - other[i][j] for j in range(len(self.rows[0])) for i in range(len(self.rows))])
def __mul__(self, other):
if isinstance(other, (int, float)) or (isinstance(other, Matrix3x3) and len(self.rows) == other.cols): # 检查是否可以进行矩阵乘法
result = [[sum(self[i][k] * other[j][k] for k in range(len(self.rows[0]))) for j in range(len(other.rows))] for i in range(len(self.rows))]
return Matrix3x3(result)
else:
raise ValueError("Invalid operation: cannot multiply matrix with incompatible dimension.")
# 示例用法
matrix1 = Matrix3x3([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix2 = Matrix3x3([[9, 8, 7], [6, 5, 4], [3, 2, 1]])
result_add = matrix1 + matrix2
result_sub = matrix1 - matrix2
result_mul = matrix1 * 2
print("Matrix addition:", result_add)
print("Matrix subtraction:", result_sub)
print("Scalar multiplication:", result_mul)
```
阅读全文
相关推荐


















