cyc*_*ter 4 python numpy linear-algebra
未能找到任何这方面的信息。如果我有两个维度相同的 mxn 矩阵,有没有办法在 numty 中对它们应用逐元素函数?为了说明我的意思:
自定义函数为 F(x,y)
第一个矩阵:
array([[ a, b],
[ c, d],
[ e, f]])
Run Code Online (Sandbox Code Playgroud)
第二个矩阵:
array([[ g, h],
[ i, j],
[ k, l]])
Run Code Online (Sandbox Code Playgroud)
有没有办法在 numpy 中使用上述两个矩阵来获得下面所需的输出
array([[ F(a,g), F(b,h)],
[ F(c,i), F(d,j)],
[ F(e,k), F(f,l)]])
Run Code Online (Sandbox Code Playgroud)
我知道我可以只做嵌套for语句,但我想可能有一种更干净的方法
对于一般功能F(x,y),您可以这样做:
out = [F(x,y) for x,y in zip(arr1.ravel(), arr2.ravel())]
out = np.array(out).reshape(arr1.shape)
Run Code Online (Sandbox Code Playgroud)
但是,如果可能的话,我建议F(x,y)以可以矢量化的方式重写:
# non vectorized F
def F(x,y):
return math.sin(x) + math.sin(y)
# vectorized F
def Fv(x,y):
return np.sin(x) + np.sin(y)
# this would fail - need to go the route above
out = F(arr1, arr2)
# this would work
out = Fv(arr1, arr2)
Run Code Online (Sandbox Code Playgroud)