MATLAB Answers

Derive input function_handle in script

5 views (last 30 days)
Sebagrei on 20 Jan 2020
Commented: Geoff Hayes on 20 Jan 2020
I have this implementation of the newton method and currently handing over the derivative manually. I tried to make the script derive the function but I just can't make it work.
Inputs currently look like this:
newtonmethod(@(x)(x-2)^2, @(x)2*(x-2), 5, 10e-10)
With the args being the actual function, the derivative, starting value and tolerance. My code looks like this:
function[x] = newtonmethod(f, df, x0, tol)
%df = diff(f); replace the input df by this statement
x = x0 - f(x0)/df(x0);
while abs(y-x) > tol && df(x) ~= 0
y = x;
x = x - f(x)/df(x);


Geoff Hayes
Geoff Hayes on 20 Jan 2020
Sebagrei - have you tried removing the lines
df = diff(f);
? diff might not return what you are expecting (see diff documentation for details)...and why overwrite the passed in value which seems to be fine?
Sebagrei on 20 Jan 2020
Hi. Thanks for the answer. The "end" must have slipped in somehow. I've commented the script to be more precise.
The point is, I would prefer not to have to hand over the derivative manually. When experimenting with diff in this context i noticed that it doesn't produce the desired results. Is there a way to get the derivative of the passed function handle inside of the script?
Geoff Hayes
Geoff Hayes on 20 Jan 2020
It you have the Symbolic Toolbox (see diff)?

Sign in to comment.

Answers (0)

Sign in to answer this question.

Translated by