How to use a "for" loop to solve n iterations of the newton-raphson method?

24 views (last 30 days)
(f,a,n) which takes three inputs: f: A function handle for a function of x. a: A real number. n: A positive integer. Does n iterations (with a for loop) of the Newton-Raphson method with starting approximation x = a. The initial guess a does not count as an iteration. Returns the nth approximation.
I have:
function r=mynewton(f,a,n)
syms x;
for i=1:n;
x(i+1)=a-f(x(i))/diff(f(x(i)));
end;
r=x(i+1);
end
I know this is incorrect because it will give me the same answer no matter what data I put as f,a or n.
Can anyone help me fix the equation in line 4 or the for loop altogether because i cannot quite get it right.

Accepted Answer

Geoff Hayes
Geoff Hayes on 10 Aug 2014
Renee - you have to use the Symbolic Toolbox to solve this problem. You could just do away with it altogether, and replace this line where the array x has been pre-allocated to the correct size. Since there are n iterations, and you actually compute up to the n+1 value then
% pre-allocate memory for the x vector
x = zeros(n+1,1);
% initialize the first element of x to be a
x(1) = a;
We do this initialization since Newton's method is defined (see Newton's Method) as
x(k+1) = x(k) - f(x(k))/f'(x(k))
Note how this is slightly different from your function in that this one only uses a on the first iteration.
Now we have to define f'(x(k)). We can approximate the derivative (in a similar manner to how you were using diff) as follows
for k=1:n
% let h be an appropriate (small) step size
h = 0.0001;
% define the derivative of the function f at x(k) as
fp = (f(x(k)+h) - f(x(k)))/h;
% now compute the x(k+1) as
x(k+1) = x(k) - f(x(k))/fp;
end
% grab the last element of x as our root
r = x(end);
And that is it. Note how in the above, we define the derivative in the same manner as the example (at the given link) using diff. Try the above and see what happens!

More Answers (0)

Community Treasure Hunt

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

Start Hunting!