How to find the derivative of the function at some value of x?
351 views (last 30 days)
reema shrestha on 1 Jul 2017
I am trying to write a code for the Newton-Raphson iteration method. So at first i created a function
Then in next M-file,i wrote
But then I try to differentiate the function
it shows error.
how do i solve the problem? I tried various ways but none of them worked. How do i call the function from previous M-file?
John D'Errico on 1 Jul 2017
MATLAB cannot do symbolic differentiation on an m-file. That would in general be impossible, since you could stick anything you wanted in there.
You have two choices:
1. Perform the differentiation in advance, using the sym tools. Then you can pass the derivative function also to your NR code.
2. Inside the NR code, use finite differencing to compute an approximation to the derivative. This is almost always adequate for Newton schemes, although care must be taken to get a good estimate, using an appropriate step size. Also, central differences are considerable more accurate, so use them whenever possible.
More Answers (2)
Karan Gill on 5 Jul 2017
Edited: Karan Gill on 17 Oct 2017
To differentiate a function and then find the value, use symbolic functions. For details, see https://www.mathworks.com/help/symbolic/create-symbolic-functions.html
>> syms f(x)
>> f(x) = x^2 -3*x + 2
x^2 - 3*x + 2
>> g = diff(f)
2*x - 3
>> g(2) % value at x = 2
>> xValues = [-10 5 88]
-10 5 88
[ -23, 7, 173]