I cannot plot the Bisection Method Code
Show older comments
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..
clc
clear all
close all
f=@(x) x^3 - x - 3;
serr=[] %empty set for plotting
sf=[]
xl=0; %initial guesses
xu=3; %initial guesses
xr1=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)
end
end
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)')
Accepted Answer
More Answers (0)
Categories
Find more on MATLAB in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!