Skip to content Skip to sidebar Skip to footer

Numpy: Subtract Matrix From All Elements Of Another Matrix Without Loop

I have two matrices X,Y of size (m x d) and (n x d) respectively. Now i want to subtract the whole matrix Y from each element of the matrix X to get a third matrix Z of size (m x n

Solution 1:

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)

Post a Comment for "Numpy: Subtract Matrix From All Elements Of Another Matrix Without Loop"