Newton's method function output.

Hello,
I have a little problem with Newton's method. I have the code and it is working but I would like to get the results such that I have the teration number n and the value of x_n according to it. Also I need the error and f(x_n) but I am only getting the x_n values on their own. The code is as follows
function [x,n,err] = newton( f, dx, x0, tol, ITMAX )
format long
f= inline(f);
dx = inline(dx);
x(1) = x0 - (f(x0)/dx(x0));
err(1) = abs(x(1)-x0);
fx=feval(f,x);
for n=2:ITMAX
if (err(n-1) >= tol) & (n <= ITMAX)
x(n) = x(n-1) - (f(x(n-1))/dx(x(n-1)));
err(n) = abs(x(n)-x(n-1));
n = n+1;
else
break
end
end
end
It would be nice if I could get the result in a table like this
disp('_________________________________________________________________________________ ')
disp(' n x_n f(x_n) error ')
disp('_________________________________________________________________________________ ')
fprintf('\n')
However I am not quite sure how to use fprint command. Any help would be appreciated. Thank you.

 Accepted Answer

Jan
Jan on 3 Jan 2016
Edited: Jan on 3 Jan 2016
The code contains several problems. E.g. you do not have to check for n < ITMAX inside the FOR loop, because the FOR itself limits n to this value already. The FOR cares for increasing n also, so omit n=n+1.
As the editor warnings show already, inline is deprecated. Use anonymous functions or function handles instead as inputs.
For fprintf:
% Before the loop:
fprintf('%10s%10s%10s%10s\n', 'n', 'x_n', 'f(x_n)', 'error');
% Inside the loop:
fprintf('%10g%10g%10g%10g\n', n-1, x(n-1), f(x(n-1)), err(n-1));
I suggest to switch to a while loop, because then you can update the values and the counter index n more consistently.

1 Comment

Hi. Thank you for your answer, it really helps, just got one more question, I have noticed that when I use n-1 in second fprintf then MATLAB doesn't show the last value that it has calculated, when changed to just n then it will not show calculations for n=1, it is not a big issue but do you think it would be possible to include all n values in that table, staring from n=0? Thanks for the suggestions too.
Figured it out, thanks! :)

Sign in to comment.

More Answers (0)

Categories

Find more on Mathematics in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!