Newtons-Raphsons method is easy to implement in Mathematica but in Matlab it seems a bit difficult. I don't get if I can pass a function to a function and how to use the derivative as a function.
newtonRaphson[f_, n_, guess_] :=
If[n == 0, guess, newtonRaphson[f, n - 1, guess - f[guess]/f'[guess]]]
newtonRaphsonOptimize[f_, n_, guess_] :=
If[n == 0, guess,
newtonRaphsonOptimize[f, n - 1, guess - f'[guess]/f''[guess]]]
It doesn't seem like you can derive neither function-handles nor functions defined in a file but I might be wrong.
There's no way to algebraically take derivatives of function handles or functions defined in m-files. You would have to do this numerically by evaluating the function at a number of points and approximating the derivative.
What you're probably wanting to do is differentiation of symbolic equations, and you need the Symbolic Math Toolbox for that. Here's an example of finding a root using the Newton-Raphson method:
You can see that the value of
xRoot
comes close to the value of the true root (which is 2) after just a couple of iterations. You could also place the function evaluation in a while loop with a condition that checks how big a difference there is between each new guess and the previous guess, stopping when that difference is sufficiently small (i.e. the root has been found):You could use an implementation like this:
And pass it function handles of both the function and its derivative. This derivative is possible to acquire by some different methods: manual differentiation, symbolic differentiation or automatic differentiation. You can also perform the differentiation numerically, but this is both slow and requires you to use a modified implementation. So I will assume you have calculated the derivative in any suitable way. Then you can call the code: