Given the function:
$$v(x,y) = x + e^{-((x-1)^2 + (y-1)^2)}$$
I am supposed to calculate the gradient of this expression in Matlab for x defined in the interval -1:0.1:0.9 and y defined in the interval -2:0.1:1.9. My task is to find the absolute value of the gradient of this function, and I'm supposed to do this two ways - first by calculating the gradient analytically by myself, and then by using Matlab's built'in gradient-function. However, I get quite different results when I do this. For the analytical part I did as follows:
[x,y] = meshgrid(-1:0.1:0.9, -2:0.1:1.9);
analytic_partialx = 1 - 2*(x-1).*exp(-((x-1).^2 + (y-1).^2));
analytic_partialy = -2*(y-1).*exp(-((x-1).^2 + (y-1).^2));
abs_gradient = sqrt(analytic_partialx.^2 + analytic_partialy.^2);
When using Matlab's built-in function I did as follows:
[x,y] = meshgrid(-1:0.1:0.9,-2:0.1:1.9);
v = x + exp(-((x-1).^2 + (y-1).^2));
[partialx,partialy] = gradient(v);
abs_gradient = sqrt(partialx.^2 + partialy.^2);
However, in the first case I get a matrix primarily containing values in the range of 1-1.5, whereas in the secand case I get a matrix primarily containing values in the range of 0-0.2. So one of my approaches is wrong here since they should have been almost completely similar. If anyone can help me by seeing what I do wrong here, then I would be extremely grateful!
I am not near Matlab at the moment. Does the gradient command have an option where you input all three of x,y,v?
Otherwise, you should divide your Matlab answer by 0.1, which is the value of dx and dy in the grid.