I cannot plot the Bisection Method Code

3 ビュー (過去 30 日間)
hgrlk
hgrlk 2019 年 4 月 17 日
コメント済み: hgrlk 2019 年 4 月 18 日
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)')

採用された回答

Geoff Hayes
Geoff Hayes 2019 年 4 月 18 日
hgrlk - the problem is that your m is equal to the size of your serr and sf plus one. So when you call
plot(1:m,serr,'-o')
the array 1:m is one element larger than serr and so the error message makes sense. You can do one of three things - initialize m to zero so that
serr=[serr error];
sf=[sf f(xr2)];
m = m+1;
are all kept in sync (here, m will now correspond to the length of serr and sf). Or you can plot your data like
plot(1:length(serr),serr,'-o')
or simply
plot(serr,'-o')
  1 件のコメント
hgrlk
hgrlk 2019 年 4 月 18 日
Oh, I get it. Thanks for the helping. I couldn't think m equal to size of set plus one.
Thanks again it works now..

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLine Plots についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by