user5806421
user5806421

Reputation:

Difference of numpy arrays of different dimensions

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

Answers (1)

Divakar
Divakar

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

Related Questions