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

26 views (last 30 days)
Kevin Osborn on 1 Oct 2021
Commented: Kevin Osborn on 1 Oct 2021
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.
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Accepted Answer

Matt Tearle on 1 Oct 2021
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 CommentsShowHide 3 older comments
Kevin Osborn on 1 Oct 2021
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.

Sign in to comment.

### Categories

Find more on Graphics Object Programming in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!