已知两个矩阵相加,并返回新矩阵,用python写
时间: 2024-03-13 18:22:26 浏览: 114
矩阵分析大作业,python.zip
以下是使用Python实现两个矩阵相加并返回新矩阵的示例代码:
```python
def matrix_addition(matrix1, matrix2):
# 获取矩阵的行数和列数
rows = len(matrix1)
cols = len(matrix1[0])
# 创建一个新的矩阵来保存结果
result = [[0 for j in range(cols)] for i in range(rows)]
# 遍历两个矩阵,将对应位置的元素相加
for i in range(rows):
for j in range(cols):
result[i][j] = matrix1[i][j] + matrix2[i][j]
return result
```
使用示例:
```python
# 定义两个矩阵
matrix1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix2 = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
# 调用函数相加矩阵
result = matrix_addition(matrix1, matrix2)
# 输出结果
for row in result:
print(row)
```
输出结果:
```
[10, 10, 10]
[10, 10, 10]
[10, 10, 10]
```
阅读全文