在两个向量上广播一个函数以获得一个2d numpy数组



我想在向量上广播函数f,这样结果就是矩阵p,其中p[I,j]=f(v[I],v[j])。我知道我可以简单地做到:

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,:])

或更狡猾:

from scipy.spatial.distance import cdist
P = cdist(v, v, metric=f) 

但我正在寻找最快、最整洁的方法。这似乎是numpy应该内置的广播功能。有什么建议吗?

我相信你搜索的是numpy.vectorize

def f(x, y):
    return x + y
v = numpy.array([1,2,3])
# vectorize the function
vf = numpy.vectorize(f)
# "transposing" the vector by producing a view with another shape
vt = v.reshape((v.shape[0], 1)
# calculate over all combinations using broadcast
vf(v, vt)
Output:
array([[ 2.,  3.,  4.],
       [ 3.,  4.,  5.],
       [ 4.,  5.,  6.]])

最新更新