Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MatLab - gradient command

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!

like image 617
Kristian Avatar asked Feb 19 '26 05:02

Kristian


2 Answers

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.

like image 126
jmetz Avatar answered Feb 20 '26 20:02

jmetz


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

like image 22
Rasman Avatar answered Feb 20 '26 20:02

Rasman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!