Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ?

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading