将一个函数广播到两个向量上得到一个2d numpy数组

2024-03-29 02:20:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在向量上广播函数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,:])

或者更老套:

^{pr2}$

但我在寻找最快最简洁的方法。 这似乎是一个广播功能,纽比应该内置。 有什么建议吗?在


Tags: 方法函数in功能forzerosrange矩阵
1条回答
网友
1楼 · 发布于 2024-03-29 02:20:19

我相信你搜索的是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.]])

相关问题 更多 >