So I have a function f(x)
where the argument x
is a row array, with dimension k
.
The function can be given an array with a number of rows >1 and is optimized to operate row-wise on arrays, clearly much faster than iterating over array rows and calling the function.
Now I would like to apply the function on a grid covering a k-dimensional space.
Let us say the k-dimension = 3.
Then
N_DIV = 2
x0 = np.linspace(0,1,N_DIV)
x1 = np.linspace(0,1,N_DIV)
x2 = np.linspace(0,1,N_DIV)
and I would like to compute the function for all combinations such as
x0 x1 x2
0 0 0
0 0 0.5
0 0.5 0
0 0.5 0.5
etc.
I thought about using np.meshgrid
so
xx, yy, zz = np.meshgrid(x0,x1,x2)
but what next? The brutal approach
prev_array=no.array([0,0,0])
for i in range(N_DIV):
for j in range(N_DIV):
for k in range(N_DIV):
prev_array = np.vstack((prev_array,
np.array([xx[i,j,k],yy[i,j,k],zz[i,j,k]])))
cannot be right, any suggestions please?
I would like to efficiently compute the functionf
over a grid covering the k-dimensional space, thanks
*** EDIT
The post Evaluate function on a grid of points has been suggested as a solution, but I fail to see how it could answer my question. They have a f(x,y)
of two scalar variables, and I see how the idea result = func(xaxis[:,None], yaxis[None,:])
. But my function takes a row vector as input, so {x,y}, and hence the idea above seems not directly applicable, to me at least, thanks again
BACKGROUND - What I am trying to achieve
Say I have a function of 3 variables
def func(x,y,z):
return x**3 - 3*y + z**2
and I want to plot it as a function of say(x,y)
, for a fixed value of z
.
I could do
N_DIV = 30
x =np.linspace(0,5,N_DIV)
y =np.linspace(0,5,N_DIV)
z =np.linspace(0,5,N_DIV)
xx , yy, zz = np.meshgrid(x,y,z)
W = func(xx,yy,zz)
import matplotlib.pyplot as plt
# Plot the surface
fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
surf = ax.plot_surface(xx[:,:,1],yy[:,:,1],W[:,:,1], cmap="Spectral",
linewidth=0)
plt.show()
worls fine and the repeated function evaluations are fast. But, if my function is defined as
def func_vect(x):
return x[0]**3 - 3*x[1] + x[2]**2
how to achieve the same result? That is, creating an array W
of output results, ready to plot using as before?
The brute force approach would be to create it by looping, but I am also confused by the following
def func2(x,y):
return x**3 - 3*y
xx2 , yy2 = np.meshgrid(x,y)
W2 = func2(xx2,yy2)
W2_loop = np.zeros((N_DIV, N_DIV))
for i in range(N_DIV):
for j in range(N_DIV):
W2_loop[i,j] = func2(x[j],y[i])
np.isclose(W2,W2_loop)
returns all True
, but I cannot figure out how to make it work in three dimensions, as (SECOND FUNDAMENTAL ISSUE)
W_loop = np.zeros((N_DIV, N_DIV,N_DIV))
for i in range(N_DIV):
for j in range(N_DIV):
for k in range(N_DIV):
W_loop[i,j,k] = func(x[k],y[j],z[i])
is different from the W
created above.
Thanks