manipulating derivative of function handle

2 次查看(过去 30 天)
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.

回答(1 个)

Bjorn Gustavsson
Bjorn Gustavsson 2021-1-23
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 个评论
Bjorn Gustavsson
Bjorn Gustavsson 2021-1-23
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.
Lukas-Marie Jean Stanislas Gamard
You're right, and thanks for the feedback, but as mentionned in the description of my function it is designed to return a vector of all approximations in order to plot them and analyse convergenge between different algorithms :)
Tack ändå!

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Symbolic Math Toolbox 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by