MatLab - gradient command
Solution 1
Actually the result is correct. When
>> x0 = 0
>> f(x0)
-1
such that the gradient is indeed 3. Similarly for x=10
, as f(10) = 119
and f(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.
Solution 2
I think you're looking at a boundary problem. Expand x
and you'll get the right answer. Remember that you are performing a numerical calculation
Kristian
Updated on June 04, 2022Comments
-
Kristian almost 2 years
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!