用python定义两个矩阵,实现矩阵的相加的相乘,并写出示例
时间: 2023-12-03 11:46:27 浏览: 153
python 实现矩阵相加
5星 · 资源好评率100%
好的,下面是Python代码实现两个矩阵的相加和相乘:
```python
# 定义两个矩阵
matrix1 = [[1, 2], [3, 4], [5, 6]]
matrix2 = [[7, 8], [9, 10], [11, 12]]
# 矩阵相加
def matrix_add(matrix1, matrix2):
result = []
for i in range(len(matrix1)):
row = []
for j in range(len(matrix1[0])):
row.append(matrix1[i][j] + matrix2[i][j])
result.append(row)
return result
# 矩阵相乘
def matrix_multiply(matrix1, matrix2):
result = []
for i in range(len(matrix1)):
row = []
for j in range(len(matrix2[0])):
sum = 0
for k in range(len(matrix2)):
sum += matrix1[i][k] * matrix2[k][j]
row.append(sum)
result.append(row)
return result
# 输出结果
print("Matrix1: ", matrix1)
print("Matrix2: ", matrix2)
print("Matrix Add: ", matrix_add(matrix1, matrix2))
print("Matrix Multiply: ", matrix_multiply(matrix1, matrix2))
```
示例输出:
```
Matrix1: [[1, 2], [3, 4], [5, 6]]
Matrix2: [[7, 8], [9, 10], [11, 12]]
Matrix Add: [[8, 10], [12, 14], [16, 18]]
Matrix Multiply: [[25, 28], [57, 64], [89, 100]]
```
阅读全文