MATLAB: Writing code for bisection method; then storing values for each iteration of the loop.

bisection methoditerationMATLABstoringvalue

Hello, I am trying to write a code for bisection method for a class project. I cant figure out why my code wont finish running and give me the root. I also need to store the values of a, b, c, x, and y for each iteration to plot them and make a table with? Can anybody help? Thank you.
clear; clc;
f=@(x)2 * x^4 +3 * x^3 - 11 * x^2 - 9 * x + 15 ;
a=input('\n Enter left point of interval ');
b=input('\n Enter right point of interval ');
toll= 1e-10;
err=abs(b-a);
c = ( a + b )/2;
if f(a) *f(b) > 0
disp 'Enter valid interval!!!');
else
c = ( a + b) /2;
toll= 1e-2;
err=abs(b-a);
while err > toll
if f(c) == 0
fprintf( 'The Root is: %4.4f\n', c)
else
c = ( a + b )/2;
x = abs( b - c);
y = abs(f(c));
if ( f(a) * f(c)) <= 0
c = b;
else
if ( f(b) * f(c)) <= 0
a = c;
end
end
end
end
end

Best Answer

Bradley - look closely at the condition for the while loop
while err > toll
. Since toll (the tolerance) is fixed, how or where does err get set? You initialize it on the previous line but never reset this variable using the new a and b. A couple of other things:
  • try and avoid using something like f(c) == 0 when comparing floats/doubles. Try a tolerance check instead similar to abs(f(c)) < eps.
  • only iterate for a maximum number of iterations so that you don't get stuck in the while loop: so either iterate until the error is less than the tolerance OR unti the max number of iterations has been reached.
  • use arrays to store values that you may want to plot outside of the loops.