Reputation:
Say I have two 2D arrays A
and B
with shape: (10, 10)
and (3, 3)
respectively.
I would like to know if there is a way to compute A - B
such that the shape is: (10, 10, 9)
without using a loop.
i.e, difference of each element of A
with every element from B
.
Upvotes: 1
Views: 34
Reputation: 221664
Use outer subtraction and then reshape -
np.subtract.outer(A,B).reshape((A.shape)+(-1,))
Or extend A
to 3D
with a singleton dim as the last one and subtract flattend B
-
A[...,None] - B.ravel() # or B.flat in place of B.ravel()
Upvotes: 2