Skip to content Skip to sidebar Skip to footer

How To Perform Element-wise Custom Function With Two Matrices Of Identical Dimension

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 illus

Solution 1:

For a general function F(x,y), you can do:

out = [F(x,y) for x,y inzip(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 FdefF(x,y):
    return math.sin(x) + math.sin(y)

# vectorized FdefFv(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)

Solution 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']])

defF(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')

Post a Comment for "How To Perform Element-wise Custom Function With Two Matrices Of Identical Dimension"