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

조회 수: 8(최근 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