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

Viewed 1057

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

2 Answers

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)

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')
Related