python怎么用函数求矩阵的和
时间: 2024-12-28 10:31:33 浏览: 4
在Python中,你可以定义一个函数来计算两个矩阵的和。首先,你需要确定这两个矩阵的维度是否一致,然后逐元素相加。这里是一个简单的例子:
```python
def matrix_addition(matrix1, matrix2):
# 检查矩阵维度是否相同
assert len(matrix1) == len(matrix2), "Matrices must have the same number of rows."
assert len(matrix1[0]) == len(matrix2[0]), "Matrices must have the same number of columns."
# 初始化一个新的空矩阵用于结果
result = [[0] * len(matrix1[0]) for _ in range(len(matrix1))]
# 逐元素相加
for i in range(len(matrix1)):
for j in range(len(matrix1[0])):
result[i][j] = matrix1[i][j] + matrix2[i][j]
return result
# 示例
matrix1 = [[1, 2], [3, 4]]
matrix2 = [[5, 6], [7, 8]]
sum_matrix = matrix_addition(matrix1, matrix2)
print(sum_matrix)
阅读全文