Matlab - finding gradient

2.4k Views Asked by At

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!

2

There are 2 best solutions below

1
On BEST ANSWER

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.

1
On

The analytic gradient that you've computed looks correct to me.

If you look at the function in the neighborhood of (x, y) = (1, 1), it looks approximately like x + exp(something near 0, quadratic in x and y); that means that its derivatives in x and y are approximately 1 and 0, so the gradient magnitude must be nearly 1.0.

That suggests that the first computation is correct, and the second (whose answers are never larger than 0.2) is wrong. You might try revising that second computation to this:

[x,y] = meshgrid(0.9:0.01:0.93,0.9:0.1:1.1);
v = x + exp(-((x-1).^2 + (y-1).^2));
[partialx,partialy] = gradient(v);
abs_gradient = sqrt(partialx.^2 + partialy.^2);

(here I've limited the domain of x and y to very near (1,1)) and then look at the actual partialx and partialy values that gradient returns to you, and see whether they're near 1 and 0, respectively.