Supose I have, in numpy, a matrix multiplication function parameterized by 2 variables x
and y
:
import numpy as np
def func(x, y):
a = np.array([[1, x],
[x, 2]])
b = np.array([[y, 2*x],
[x, np.exp(y+x)]])
M = np.array([[3.2, 2*1j],
[4 , 93]])
prod = a @ M @ b
final = np.abs(prod[0,0])
return final
I can run this function easily for any two numerical values, e.g. func(1.1, 2.2)
returns 129.26...
.
So far so good, but now I want to run this for several values of x
and y
, e.g. x=np.linspace(0,10,500)
and y=np.linspace(0,10,500)
. I want to pair these 500 values in a one-to-one correspondence, that is the first one in the x
list with the first one in the y
list, the second one with the second one, etc.
I can do that by adding a for
loop inside the function but the procedure becomes extremely slow in my actual code (which is more computationally demanding than this example here). What I would like to ask for support is how to do this faster with only numpy functions? Is that what the numpy ufunc
's meant for? I've never looked into it.