如何使用相同维度的两个矩阵执行逐元素的自定义函数 [英] How to perform element-wise custom function with two matrices of identical dimension
问题描述
未能找到任何有关此的信息.如果我有两个相同维度的m x n矩阵,有没有办法对它们应用numpty的逐个元素函数?为了说明我的意思:
Haven't been able to find any information on this. If I have two m x n matrices of identical dimension, is there a way to apply an element-wise function in numpty on them? To illustrate my meaning:
自定义函数为F(x,y)
Custom function is F(x,y)
第一矩阵:
array([[ a, b],
[ c, d],
[ e, f]])
第二矩阵:
array([[ g, h],
[ i, j],
[ k, l]])
是否可以使用numpy中的上述两个矩阵在下方获得所需的输出
Is there a way to use the above two matrices in numpy to get the desired output below
array([[ F(a,g), F(b,h)],
[ F(c,i), F(d,j)],
[ F(e,k), F(f,l)]])
我知道我可以为嵌套
语句,但是我认为可能会有更简洁的方法
I know I could just do nested for
statements, but I'm thinking there may be a cleaner way
推荐答案
对于常规函数 F(x,y)
,您可以执行以下操作:
For a general function F(x,y)
, you can do:
out = [F(x,y) for x,y in zip(arr1.ravel(), arr2.ravel())]
out = np.array(out).reshape(arr1.shape)
但是,如果可能的话,我建议以可以向量化的方式重写 F(x,y)
:
However, if possible, I would recommend rewriting F(x,y)
in such a way that it can be vectorized:
# 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)
这篇关于如何使用相同维度的两个矩阵执行逐元素的自定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!