manipulating derivative of function handle
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Lukas-Marie Jean Stanislas Gamard
le 23 Jan 2021
Commenté : Lukas-Marie Jean Stanislas Gamard
le 23 Jan 2021
I have a problem when trying use function handles and derivatives.
This is my code:
syms x
f = @(x) x^2 - 9*x -12*sin(3*x+1)+20; % the given function
f1 = matlabFunction(diff(f(x))); % derivative of the function
g = @(x) x - f(x)/f1(x); % create a new function (Newton's method)
% I iterate g over a start value x0 and store the results in an array)
When I run it, g does not compute a value all the way, and gives me something like this for [x0 g(x0)]:
I am quite new to Matlab. Can anyone spot the issue? I fell like it has something to do with the division in g.
0 commentaires
Réponses (1)
Bjorn Gustavsson
le 23 Jan 2021
When you do this it is easy to confuse things when trying to take 2-3 steps at once (in my experience...). Do it stepwise:
f = x^2 - 9*x -12*sin(3*x+1)+20; % Symbolic definition of f
df = diff(f,x); % Symbolic derivative of f
F = matlabFunction(f); % function-handle for f
F1 = matlabFunction(df); % function-handle for df
g = @(x) x - F(x)./F1(x); % function-handle for g
HTH
4 commentaires
Bjorn Gustavsson
le 23 Jan 2021
The "problem" in your function is that you save all the values of x in the while-loop (x(k+1)=g(x(k)) will store the new value in the k+1-th element of x). That way you can track the progression of your root-finding, which might be interesting, but will become very memory-consuming if the convergence is poor. You could change the design to use 2 variables x_next and x_prev if you just want to get the final solution.
Voir également
Catégories
En savoir plus sur Symbolic Math Toolbox dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!