简体   繁体   English

numpy:从另一个矩阵的所有元素中减去矩阵而没有循环

[英]Numpy: subtract matrix from all elements of another matrix without loop

I have two matrices X,Y of size (mxd) and (nxd) respectively. 我有两个分别为(mxd)和(nxd)的矩阵X,Y。 Now i want to subtract the whole matrix Y from each element of the matrix X to get a third matrix Z of size (mxnxd). 现在,我想从矩阵X的每个元素中减去整个矩阵Y,以获得大小为(mxnxd)的第三个矩阵Z。 Using loops it would look this: 使用循环看起来像这样:

Z = [(Y-x) for x in X]

but i want to avoid loops and use numpy only. 但我想避免循环并仅使用numpy。

If i understand correctly, here is a small demo: 如果我正确理解,这是一个小演示:

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]

Result: 结果:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM