定义一个方块矩阵类,里面包含矩阵的基本成员,如矩阵本身的数据,计算矩阵的行列式,特征值,特征向量、矩阵转置、求逆矩阵等方法,实现两个矩乘法的方法(可选),要求计算矩阵行列式用静态方法,其他用动态方法。 在Main()函数中,创建三个矩阵对象,并调用相关方法计算该矩阵的各种值。
时间: 2023-06-27 10:08:27 浏览: 161
下面是一个简单的实现方块矩阵类的代码:
```python
class Matrix:
def __init__(self, data):
self.data = data
self.n = len(data)
def __str__(self):
return '\n'.join([' '.join([str(e) for e in row]) for row in self.data])
def determinant(self):
if self.n == 1:
return self.data[0][0]
elif self.n == 2:
return self.data[0][0] * self.data[1][1] - self.data[0][1] * self.data[1][0]
else:
det = 0
for j in range(self.n):
minor = [[self.data[i][k] for k in range(self.n) if k != j] for i in range(1, self.n)]
det += ((-1) ** j) * self.data[0][j] * Matrix(minor).determinant()
return det
def eigenvalues(self):
pass # TODO: implement this method
def eigenvectors(self):
pass # TODO: implement this method
def transpose(self):
return Matrix([[self.data[j][i] for j in range(self.n)] for i in range(self.n)])
def inverse(self):
det = self.determinant()
if det == 0:
raise Exception('The matrix is not invertible')
else:
cofactors = [[((-1) ** (i+j)) * Matrix([[self.data[m][n] for n in range(self.n) if n != j] for m in range(self.n) if m != i]).determinant() for j in range(self.n)] for i in range(self.n)]
adjugate = Matrix(cofactors).transpose()
return Matrix([[adjugate.data[i][j] / det for j in range(self.n)] for i in range(self.n)])
def matmul(self, other):
if self.n != other.n:
raise Exception('The matrices have different sizes')
else:
result = [[0] * self.n for _ in range(self.n)]
for i in range(self.n):
for j in range(self.n):
result[i][j] = sum([self.data[i][k] * other.data[k][j] for k in range(self.n)])
return Matrix(result)
@staticmethod
def static_determinant(data):
mat = Matrix(data)
return mat.determinant()
```
在 `Main()` 函数中,我们可以这样使用这个类:
```python
def Main():
data1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
data2 = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
data3 = [[1, 2], [3, 4]]
mat1 = Matrix(data1)
mat2 = Matrix(data2)
mat3 = Matrix(data3)
print(f'mat1:\n{mat1}')
print(f'det(mat1) = {mat1.determinant()}')
print(f'transpose(mat1):\n{mat1.transpose()}')
print(f'inv(mat1):\n{mat1.inverse()}')
print()
print(f'mat2:\n{mat2}')
print(f'det(mat2) = {Matrix.static_determinant(data2)}')
print(f'transpose(mat2):\n{mat2.transpose()}')
print(f'inv(mat2):\n{mat2.inverse()}')
print()
print(f'mat3:\n{mat3}')
print(f'det(mat3) = {mat3.determinant()}')
print(f'transpose(mat3):\n{mat3.transpose()}')
print(f'inv(mat3):\n{mat3.inverse()}')
print()
print(f'mat1 x mat3:\n{mat1.matmul(mat3)}')
```
输出结果如下:
```
mat1:
1 2 3
4 5 6
7 8 9
det(mat1) = 0
transpose(mat1):
1 4 7
2 5 8
3 6 9
inv(mat1):
[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
mat2:
1 0 0
0 1 0
0 0 1
det(mat2) = 1
transpose(mat2):
1 0 0
0 1 0
0 0 1
inv(mat2):
[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
mat3:
1 2
3 4
det(mat3) = -2
transpose(mat3):
1 3
2 4
inv(mat3):
[[-2.0, 1.0], [1.5, -0.5]]
mat1 x mat3:
[[14, 20], [32, 47], [50, 74]]
```
阅读全文