用python实现矩阵乘法
时间: 2023-09-24 09:09:57 浏览: 94
以下是使用Python实现矩阵乘法的示例代码:
```
# 定义两个矩阵
matrix1 = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
matrix2 = [[10, 11, 12],
[13, 14, 15],
[16, 17, 18]]
# 获取矩阵的行数和列数
rows1 = len(matrix1)
cols1 = len(matrix1[0])
rows2 = len(matrix2)
cols2 = len(matrix2[0])
# 确认两个矩阵可以相乘
if cols1 != rows2:
print("两个矩阵无法相乘")
else:
# 创建一个新矩阵来存储结果
result = [[0 for j in range(cols2)] for i in range(rows1)]
# 进行矩阵乘法运算
for i in range(rows1):
for j in range(cols2):
for k in range(cols1):
result[i][j] += matrix1[i][k] * matrix2[k][j]
# 打印结果
for row in result:
print(row)
```
运行以上代码,将得到以下输出:
```
[84, 90, 96]
[201, 216, 231]
[318, 342, 366]
```
阅读全文