用python语言写一个实现矩阵运算的代码
时间: 2024-03-31 10:33:53 浏览: 95
好的,以下是一个简单的 Python 代码,实现了基本的矩阵加法、矩阵减法、矩阵数乘和矩阵乘法:
```python
# 定义矩阵加法函数
def matrix_addition(matrixA, matrixB):
if len(matrixA) != len(matrixB) or len(matrixA[0]) != len(matrixB[0]):
return None
result = []
for i in range(len(matrixA)):
row = []
for j in range(len(matrixA[0])):
row.append(matrixA[i][j] + matrixB[i][j])
result.append(row)
return result
# 定义矩阵减法函数
def matrix_subtraction(matrixA, matrixB):
if len(matrixA) != len(matrixB) or len(matrixA[0]) != len(matrixB[0]):
return None
result = []
for i in range(len(matrixA)):
row = []
for j in range(len(matrixA[0])):
row.append(matrixA[i][j] - matrixB[i][j])
result.append(row)
return result
# 定义矩阵数乘函数
def matrix_scalar_multiplication(matrix, scalar):
result = []
for i in range(len(matrix)):
row = []
for j in range(len(matrix[0])):
row.append(matrix[i][j] * scalar)
result.append(row)
return result
# 定义矩阵乘法函数
def matrix_multiplication(matrixA, matrixB):
if len(matrixA[0]) != len(matrixB):
return None
result = []
for i in range(len(matrixA)):
row = []
for j in range(len(matrixB[0])):
sum = 0
for k in range(len(matrixB)):
sum += matrixA[i][k] * matrixB[k][j]
row.append(sum)
result.append(row)
return result
# 测试代码
A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
B = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
print(matrix_addition(A, B))
print(matrix_subtraction(A, B))
print(matrix_scalar_multiplication(A, 2))
print(matrix_multiplication(A, B))
```
输出结果如下:
```
[[10, 10, 10], [10, 10, 10], [10, 10, 10]]
[[-8, -6, -4], [-2, 0, 2], [4, 6, 8]]
[[2, 4, 6], [8, 10, 12], [14, 16, 18]]
[[30, 24, 18], [84, 69, 54], [138, 114, 90]]
```
希望这个代码能帮助到你!
阅读全文