I must write a program with bisection methot which has initial guesses as xl=0 xu=3. The iterations must end when | Ea | < 10^(-3) . xr represent the current root. I must plot | Ea | versus i and also f(xr) versus i.
Also my output must be print the i , xl , xu, f(xl), f(xu), xr, f(xr), | Ea | in each iteration.
I try to do plotting but when I run my code there is:
Error using plot
Vectors must be the same length.
NOTE: I want to plot with using set because I think it is easier to understand for me.
THANKS..
clcclear allclose allf=@(x) x^3 - x - 3;serr=[] %empty set for plotting
sf=[]xl=0; %initial guesses
xu=3; %initial guessesxr1=100;error=100; %initial error, here we assumed %100 error at the beginning
tolerance=1e-03; %stopping criteria
fl=f(xl);fu=f(xu);fr = f(xr1);m=1; %counter for while loop
display('BISECTION METHOD')display('---------------------')fprintf('%10s %10s %10s %10s %10s %10s %10s %10s\n','m','xl','xu','f(xl)','f(xu)','f(xl)','f(xu)','|Ea|')for i=1:1:1 fprintf('%2.0f %12.5f %12.5f %12.5f %12.5f %12.5f %12.5f %12.5f\n', m, xl, xu,f(xl),f(xu), xr1,f(xr1), error) while error>tolerance xr2 = (xu+xl)/2; fr=f(xr2); if sign(fr)==sign(fl) xl = xr2; fl = fr; else xu = xr2; fu = fr; xr1=xr2; xr2 = (xl+xu)/2; end error = abs(xr2-xr1)/xr2*100; serr=[serr error]; sf=[sf f(xr2)]; m = m+1; fprintf('%2.0f %12.5f %12.5f %12.5f %12.5f %12.5f %12.5f %12.5f\n', m, xl, xu,f(xl),f(xu), xr2,f(xr2), error) endend subplot(1,2,1)plot(1:m,serr,'-o')xlabel(' i')ylabel ('error')subplot(1,2,2)plot(1:m,sf,'-o')xlabel(' i')ylabel ('f(xr)')
Best Answer