如何在下面编写此代码单元的矢量化版本?代码应该完全矢量化,没有for循环,使用np.meshgrid和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