I have a grid of xy-coordinates that I generate using np.meshgrid
. The spacing in x-direction is constant, the y-coordinates are scaled, as a function of x. In this specific case, this results in a cloud of points that lie on a trapezoid, with a side length of 2 on the left and 1 on the right side. I have a function f(x, y)
, and I want to get the gradient of that function in y-direction and in the direction of each row of points. How can I use np.gradient
with xy-arguments to do this? I find the documentation somewhat confusing.
x = np.linspace(0, 1, num=20)
y = np.linspace(-1/2, 1/2, num=10)
x_grid, y_grid = np.meshgrid(x, y)
y_grid = y_grid * (2 - x_grid)
f = x_grid ** 2 - y_grid ** 3 # example function
gradient = np.gradient(f, x_grid, y_grid) # something like this?
# with gradient[0] being in the row-direction (in xy-space) and gradient[0] being in y-direction