Formatting code to display multiple results.

So, I'd like to alter the following code which I have written (Newton's Method), so that it not only outputs the final approximation of the root but each approximation for each iteration of the method. See what I'm saying? How would you suggest that I do this so that it's displayed somewhat neatly in the command window?
function xn = Newton (f, df, xi, tol)
xo = xi;
xn = xo - f(xo)/df(xo);
k = 0;
while ((abs(xn - xo))/(abs(xn)) > tol)
if (k <= 100)
xn = xo - f(xo)/df(xo);
k = k + 1;
else
warning('Maximum number of iterations has been reached')
break;
end
end

2 件のコメント

David
David 2013 年 10 月 29 日
Using fprintf would be best, apparently. However, I have no clue how to use this for data formatting and the help section didn't do much to clear it up.
sixwwwwww
sixwwwwww 2013 年 10 月 29 日
just make a matrix like this
fprintf('Iteration #: %f and approximation value:%f\n', k, xn);

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

 採用された回答

sixwwwwww
sixwwwwww 2013 年 10 月 29 日

1 投票

Dear David, you can output iteration number and iteration values as follows:
function [xn, iterations] = Newton (f, df, xi, tol) % output parameter "iteration" store iteration number and iteration values in cell array
xo = xi;
xn = xo - f(xo)/df(xo);
k = 0;
while ((abs(xn - xo))/(abs(xn)) > tol)
if (k <= 100)
xn = xo - f(xo)/df(xo);
k = k + 1;
iteration{k, 1} = k;
iteration{k, 2} = xn;
else
warning('Maximum number of iterations has been reached')
break;
end
end
I hope it helps. Good luck!

4 件のコメント

David
David 2013 年 10 月 29 日
Thanks, off topic but is there a problem with my code above? Should I be assigning xn to xo at the start of each iteration of the loop?
sixwwwwww
sixwwwwww 2013 年 10 月 29 日
Yes you should replace xo with previous value of xn at each iteration. the other way to solve display problem is that you can store all iteration results in one matrix and display them using
disp
before end of your function
David
David 2013 年 10 月 29 日
Fixed, Thanks.
sixwwwwww
sixwwwwww 2013 年 10 月 29 日
You are welcome

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2013 年 10 月 29 日

コメント済み:

2013 年 10 月 29 日

Community Treasure Hunt

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

Start Hunting!

Translated by