How can I write a vectorized version of this code cell below? The code should be fully vectorized, with no for-loops, using np.meshgrid and np.linspace?
def eval_on_grid_unvectorized(func, extent, numsteps):
"""Evaluates func(x1, x2) for each combination in a 2D grid.
func: callable - function to evaluate for each grid element
extent: tuple - grid extent as (x1min, x1max, x2min, x2max)
numsteps: int - number of grid steps (same for each
dimension)
"""
x1min, x1max, x2min, x2max = extent
x1 = np.empty((numsteps, numsteps))
x2 = np.empty((numsteps, numsteps))
y = np.empty((numsteps, numsteps))
for i in range(numsteps):
for j in range(numsteps):
x1[i,j] = x1min + j*(x1max-x1min)/(numsteps-1)
x2[i,j] = x2min + i*(x2max-x2min)/(numsteps-1)
y[i,j] = func(x1[i,j], x2[i,j])
return x1, x2, y
Your function, without the
y; producesMeshgrid and linspace can do the same:
But as Jérôme points out, as long as
funccan only work with scalar values, you can't "vectorize", in the sense of doing fast whole array calculations.If the func is something like
x+y, then we can simply pass the arrays to it:The key to what we normally call
vectorizationinnumpyis to write the calculation in a way that uses the compiled numpy methods, and operators. It requires real knowledge ofnumpy; there isn't a magic short cut to let you jump from scalar Python calculations to efficientnumpyones.