manipulating derivative of function handle
2 ビュー (過去 30 日間)
古いコメントを表示
Lukas-Marie Jean Stanislas Gamard
2021 年 1 月 23 日
コメント済み: Lukas-Marie Jean Stanislas Gamard
2021 年 1 月 23 日
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 件のコメント
回答 (1 件)
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
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.
参考
カテゴリ
Help Center および File Exchange で Symbolic Math Toolbox についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!