You can use np.einsum
after calculating the differences in a broadcasted way
, like so –
ab = a[:,None,:] - b
out = np.einsum('ijk,ijk->ij',ab,ab)
Or use scipy's cdist
with its optional metric argument set as 'sqeuclidean'
to give us the squared euclidean distances as needed for our problem, like so –
from scipy.spatial.distance import cdist
out = cdist(a,b,'sqeuclidean')