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.

Answers (1)

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 Comments

I changed my code according to your suggestion and it still does not compute all the way:
function vect = newtonVekt(x0, n)
% function that returns a vector of all approximations
syms x
f = x^2 - 9*x -12*sin(3*x+1)+20;
df = diff(f,x);
F = matlabFunction(f);
F1 = matlabFunction(df);
g = @(x) x - F(x)./F1(x);
x(1) = x0;
x(2) = g(x0);
k = 1;
while k < n
k = k + 1;
x(k+1) = g(x(k));
end
vect = x;
end
I get an array of fractions as a result. Moreover, I don't think my differentiation of a function handle was a problem, according to this post.
I think my problem was that I was using syms x and then naming x my answers array. I changed the array to y and it worked.
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.
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å!

Sign in to comment.

Categories

Community Treasure Hunt

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

Start Hunting!