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

24 views (last 30 days)

Show older comments

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 Comments

### 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 Comments

Kevin Osborn
on 1 Oct 2021

### More Answers (0)

### See Also

### Community Treasure Hunt

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

Start Hunting!