I am trying to learn various functions and commands in MatLab. I have a question regarding the gradient command.
Say I define the following:
x = 0:1:10;
f = @(x) x.^2 + 2*x -1;
h = gradient(f(x))
This then gives me the following vector:
h = 3 4 6 8 10 12 14 16 18 20 21
I see that the values are correct when x is between 1 and 9, but this is incorrect for x = 0 and x = 10. When x = 0, the gradient should be 2, and when x = 10, the gradient should be 22. So why does MatLab give erroneous answers for these two input values?
If anyone could explain this to me I would greatly appreciate it!
Actually the result is correct. When
such that the gradient is indeed 3. Similarly for
x=10, asf(10) = 119andf(9)=98, so the gradient is indeed = 21.The discrepancy between these results and the analytical result is because the gradient is a numerical approximation to the derivative with associated boundary issues.
Consider further what would have happened if you had given less data points, say only two points – the algorithm would give you the gradient as the difference between the points divided by the interval. This is what is happening at the boundary.