如何使用Python添加两个矩阵?
在python中添加2个矩阵的最简单方法是将它们循环并逐个添加元素。例如,
X = [[1,2,3], [4,5,6], [7,8,9]] Y = [[9,8,7], [6,5,4], [3,2,1]] result = [[0,0,0], [0,0,0], [0,0,0]] for i in range(len(X)): for j in range(len(X[0])): result[i][j] = X[i][j] + Y[i][j] for r in result: print(r)
这将给出输出:
[10, 10, 10] [10, 10, 10] [10, 10, 10]
您还可以使用支持此功能的numpy模块。
import numpy as np X = np.matrix([[1, 2], [3, 4]]) Y = np.matrix([[2, 2], [2, 2]]) result = X + Y print(result)
这将给出输出:
matrix([[3, 4], [5, 6]])