numpy elementwise outer product

Extend A and B to 3D keeping their first axis aligned and introducing new axes along the third and second ones respectively with None/np.newaxis and then multiply with each other. This would allow broadcasting to come into play for a vectorized solution.

Thus, an implementation would be –

A[:,:,None]*B[:,None,:]

We could shorten it a bit by using ellipsis for A’s : :,: and skip listing the leftover last axis with B, like so –

A[...,None]*B[:,None]

As another vectorized approach we could also use np.einsum, which might be more intuitive once we get past the string notation syntax and consider those notations being representatives of the iterators involved in a naive loopy implementation, like so –

np.einsum('ij,ik->ijk',A,B)

Leave a Comment