How to put a plot of iteration count vs relative error?

17 views (last 30 days)
Hello guys, im not very good with matlab and i just have to ask a quick question. I need to put a plot of the relative error of the bisection method vs the iteration count. 'You should also include a plot of the relative error as a function of the iteration number. ' is what my teacher said. Here is the code I have at the moment.
if true
f = @(x) cos(x)-x;
x1 = 0.7;
x2 = 0.8;
TOL = 1e-4;
counter = 0;
while abs(x2-x1) > TOL
xmid = (x2+x1)/2;
if (f(x2)*f(xmid)) <0
x2 = xmid;
else
x1 = xmid;
relerr = abs(x1 - x2) / xmid
counter = counter + 1;
end
figure
hold on
plot(counter, relerr)
axis ([0 11 0 0.0002])
Now whenever i try to create the plot i get something that is completely empty. And if i put the create plot command inside the while loop, i get 11 empty plots. i use an fprintf command to print out results for error, iterations and the root of the fn and they all work fine, but the only thing i cant get to work is the plot. Anyone got any ideas?

Accepted Answer

Walter Roberson
Walter Roberson on 18 May 2015
Change the
relerr = abs(x1 - x2) / xmid
counter = counter + 1;
to
counter = counter + 1;
relerr(counter) = abs(x1 - x2) / xmid;
Change the
plot(counter, relerr)
to
plot(relerr)
By the way: consider that when you write
if something
do first thing
else
do second thing
make an assignment
end
then the assignment is only done if the "something" was false. The "else" part extends right to the "end" (or next "elseif").

More Answers (0)

Categories

Find more on Contour Plots 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!