Skip to content
Advertisement

How to create a numpy 2-D array whose elements depend on elements of two lists already fixed

Example:

Let

A = np.array([1,2,3,5,7])
B = np.array([11,13,17,19,23]) 

and I would like to create a matrix C of size (5,5) whose elements are

c_ij = f(a[i],b[j])

where f is a fixed function for example f(x,y) = x*y + x + y which means

c_ij = a[i]*b[j] + a[i] + b[j]

In the case where c_ij depends on i and j only and does not depend on the lists A and B, we can use np.fromfunction(lambda i,j: f(i,j), (5,5)) but it’s not the case.

I would like to know how we can do that ?

Advertisement

Answer

Is this what you want:

def bar(arr1, arr2, func):
    ind1, ind2 = np.meshgrid(range(len(arr1)), range(len(arr2)))
    x = arr1[ind1]
    y = arr2[ind2]
    return func(x, y)

bar(A, B, f)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement