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.

 採用された回答

Jan
Jan 2016 年 1 月 3 日
編集済み: Jan 2016 年 1 月 3 日

0 投票

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 件のコメント

Wojciech Zaremba
Wojciech Zaremba 2016 年 1 月 3 日
編集済み: Wojciech Zaremba 2016 年 1 月 3 日
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! :)

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMathematics についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by