2

我想在向量上广播一个函数 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 应该内置的广播功能。有什么建议么?

4

1 回答 1

1

我相信您搜索的是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.]])
于 2014-09-18T23:44:35.690 回答