MATLAB: How to get the function to form the derivative for Newton-Method

derivativesMATLABnewton method

Hey everyone,
I'm new here so please bear with me. I want to write a Newton-Function to practise in Matlab and find zero points. However, it works fine if I give the derivative. But I want it to form the derivative itself, since I am prone of making dumb mistakes in exams. Here is my code (I hope I did insert it correctly):
function [x] = Newton(f,x,m)
syms x
fderiv = diff(f,x); %I'm trying to tell him to define the derivative of f as fderiv to use it afterwards
for i = 1:m
x(i+1) = x(i) - f(x(i))/fderiv(x(i)) ; % The newton formula x(n) = x(n-1) - f(x(n-1))/f'(x(n-1)
if abs(x(i+1)-x(i)) < 2*10^(-5) %criteria to abort nonsense iteration
break
end
end
disp(x(end))
end
So I give him f , x (as a starting value) and m as iteration steps:
f =@ (x) 2*x^2-5; x = 1.5 ; m = 15 ;
I get following error:
>> Newton(f,x,m)
Error using sym/subsindex (line 836)
Invalid indexing or function definition. Indexing must follow MATLAB
indexing. Function arguments must be symbolic variables, and function
body must be sym expression.
Error in sym/subsref (line 881)
R_tilde = builtin('subsref',L_tilde,Idx);
Error in Newton (line 20)
x(i+1) = x(i) - f(x(i))/fderiv(x(i)) ;
Maybe somebody knows what I could do, I'd really appreciate it. Have a great day,
Lg,
Marcus

Best Answer

function [b] = Newton(f,x,m)
b=x;
syms x
fderiv = diff(f,x);
for i = 1:m
b(i+1) = b(i) - f(b(i))/subs(fderiv,b(i)) ;
if abs(b(i+1)-b(i)) < 2*10^(-5)
break
end
end
disp(b(end))
end