MATLAB: How to calculate derivative of function inside of another function

derivativefunctionMATLAB

I have been searching for how to calculate the symbolic derivative of a function to use with my Newton's Method function. Currently I have to hand calculate the derivatives and pass it into my Newton's Method Function, I save both the original function and derivative as separate functions.
My function code is:
% M- file :f5.m
% define function to evaluate real zero using Newton's method
function y = f5(x)
y = x^3-2*x+2;
(derivative is hand calculated and entered the same way)
My Newton's method code starts with:
function q = newton(f, fprime, x0, maxim, epsi, delta)
f,fprime are my defined functions
x0 is starting point
maxim,epsi,delta are my tolerances
from here my function works great but I want the code to work like this:
function q = newton(f, x0, maxim, epsi, delta)
fprime = diff(f,x) <-calculate derivative of f and save as fprime
so that fprime = 3x^2-2 and I can calculate fprime at a point xo by feval(f,x0)
Any help on how to do this would be appreciated greatly. Thanks!

Best Answer

function q = newton(f, x0, maxim, epsi, delta)
syms x
fprime = diff(f(x),x) % calculate derivative of f and save as fprime
This is not going to work unless f(x) is a simple formula -- for example, f(x) must not have any "if" or "for" statements that depend upon x.
Related Question