I want to broadcast a function f over a vectors so that the result is a matrix P where P[i,j] = f(v[i], v[j]). I know that I can do it simply:
P = zeros( (v.shape[0], v.shape[0]) )
for i in range(P.shape[0]):
for j in range(P.shape[0]):
P[i, j] = f(v[i,:], v[j,:])
or more hacky:
from scipy.spatial.distance import cdist
P = cdist(v, v, metric=f)
But I am looking for the fastest and neatest way to do it. This seems like a function of broadcasting that numpy should have built-in. Any suggestions?
cdistlooks like a pretty clean way of doing this. In the case of a callablemetric,cdistdoes exactly what your code is doing.f(a,b)takes 2 1d arrays, and returns a scalar?f1 = functools.partial(cdist, metric=f)would hide thecdistusage.P[i, j]... do you need all the distance matrix or only to find the closest points for some reason... in that case, checkscipy.spatial.distance.cKDTree()..