manipulating derivative of function handle
이전 댓글 표시
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
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
Lukas-Marie Jean Stanislas Gamard
2021년 1월 23일
편집: Lukas-Marie Jean Stanislas Gamard
2021년 1월 23일
Lukas-Marie Jean Stanislas Gamard
2021년 1월 23일
편집: Lukas-Marie Jean Stanislas Gamard
2021년 1월 23일
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
2021년 1월 23일
카테고리
도움말 센터 및 File Exchange에서 Symbolic Math Toolbox에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!