How do I display my secant method iteration values in a table?

5 ビュー (過去 30 日間)
Kevin Osborn
Kevin Osborn 2021 年 10 月 1 日
コメント済み: Kevin Osborn 2021 年 10 月 1 日
Here is my code for the secant method approximation of the function.
func = @(x) 2*exp(-2*x) + 4*sin(x) - 2*cos(2*x);
x1 = 2.5;
x2 = 2.4;
tol = 1e-9;
f1 = func(x1);
dx = inf;
iter = 0;
while abs(dx) > tol
iter = iter + 1;
f2 = func(x2);
dx = (x2 - x1)*f2/(f2 - f1);
x1 = x2;
f1 = f2;
x2 = x2 - dx;
end
x2
iter
It says that it takes 5 iterations to get to the root. I would like to be able to display each of these iterations with what value they approximate for the root.
Could someone please help me with the code that would be required to do that? Thank you.

採用された回答

Matt Tearle
Matt Tearle 2021 年 10 月 1 日
If you want to display things nicely, you can use fprintf to format things into text. If the primary concern is getting the values to display, you should save the information you need in each pass through the loop. Here's both:
...
dx = inf;
iter = 0;
% start a record of iteration info
dispdata = [iter;x1;x2];
while abs(dx) > tol
iter = iter + 1;
f2 = func(x2);
dx = (x2 - x1)*f2/(f2 - f1);
x1 = x2;
f1 = f2;
x2 = x2 - dx;
% add the latest info to the list
dispdata(:,iter+1) = [iter;x1;x2];
end
% ugly
disp(dispdata)
% pretty
fprintf(" k: x1 x2\n")
fprintf("----------------------\n")
fprintf("%2d: %7.4f %7.4f\n",dispdata)
If you want to see the iterations as they happen, you should do a nice fprintf inside the loop for each iteration instead.
  4 件のコメント
Kevin Osborn
Kevin Osborn 2021 年 10 月 1 日
Thank you so much. I think I will just use the basic plot, I just wanted to see it graphically, nothing too fancy. It's nice to know how to get it to plot individual points as it runs though. I will probably use that in the future somewhere. Thanks again.

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

その他の回答 (0 件)

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by