我有两个矩阵X,Y,分别是大小(m x d)和(n x d)。现在我想从矩阵X的每个元素中减去整个矩阵Y,以得到大小为(m×n×d)的第三矩阵Z.使用循环看起来像这样:
Z = [(Y-x) for x in X]
但我想避免循环并仅使用numpy。
答案 0 :(得分:0)
如果我理解正确,这是一个小型演示:
In [81]: X = np.arange(6).reshape(2,3)
In [82]: Y = np.arange(12).reshape(4,3)
In [83]: X
Out[83]:
array([[0, 1, 2],
[3, 4, 5]])
In [84]: Y
Out[84]:
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
In [85]: X.shape
Out[85]: (2, 3)
In [86]: Y.shape
Out[86]: (4, 3)
In [87]: Z = Y - X[:, None]
结果:
In [95]: Z
Out[95]:
array([[[ 0, 0, 0],
[ 3, 3, 3],
[ 6, 6, 6],
[ 9, 9, 9]],
[[-3, -3, -3],
[ 0, 0, 0],
[ 3, 3, 3],
[ 6, 6, 6]]])
In [96]: Z.shape
Out[96]: (2, 4, 3)