How to perform element-wise custom function with two matrices of identical dimension

大憨熊 提交于 2020-06-15 18:54:06

问题


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:

Custom function is F(x,y)

First Matrix:

array([[ a, b],
       [ c, d],
       [ e, f]])

Second Matrix:

array([[ g, h],
       [ i, j],
       [ k, l]])

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


回答1:


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)

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)



回答2:


You can use numpy.vectorize function:

import numpy as np

a = np.array([[ 'a', 'b'],
       [ 'c', 'd'],
       [ 'e', 'f']])

b = np.array([[ 'g', 'h'],
       [ 'i', 'j'],
       [ 'k', 'l']])

def F(x,y):
    return x+y

F_vectorized = np.vectorize(F)

c = F_vectorized(a, b)

print(c)

Output:

array([['ag', 'bh'],
       ['ci', 'dj'],
       ['ek', 'fl']], dtype='<U2')


来源:https://stackoverflow.com/questions/61899911/how-to-perform-element-wise-custom-function-with-two-matrices-of-identical-dimen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!