How do I get my function to form the derivative for Newton-Method
11 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Marcus Schlitter
le 27 Nov 2019
Commenté : Marcus Schlitter
le 28 Nov 2019
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
0 commentaires
Réponse acceptée
David Hill
le 27 Nov 2019
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
Plus de réponses (1)
Steven Lord
le 27 Nov 2019
The diff function doesn't know how to operate on arbitrary function handles, including anonymous function handles. For functions than can be evaluted for symbolic variables, like the one you've specified, you could evaluate it and call diff on the resulting symbolic expression.
f =@ (x) 2*x^2-5; x = 1.5 ; m = 15 ;
syms x
fs = f(x)
dfs = diff(fs, x)
Voir également
Catégories
En savoir plus sur Calculus dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!