my code does not loop
1 view (last 30 days)
Show older comments
am new in MATLAB adn I am trying to calculate 3 different equations root using bisection method with the code below. it only calculates first equation and does not loop. can you haelp me?
clc,clear, clear all
fs = {@(x)sin(x^2)+x-1;
@(x)x^10-1;
@(x)x^5-2*x^3+x^2-1};
xl=[0 0 0]; %lower bound
xu=[1.2 1.5 1.6]; %upper bound
e=[0.01e-2 0.005e-2 0.002e-2]; %specified error tolerances
iter=0;
err=1;
for i=1:3
if fs{i}(xl(i))*fs{i}(xu(i))>0
fprintf('No Root at specified interval\n')
else
lower=xl(i);
upper=xu(i);
while(err>e)
iter = iter+ 1;
xr = (lower+upper)/2;
if fs{i}(xl(i))*fs{i}(xr)<0
upper=xr;
else
lower=xr;
end
err=abs((upper-lower)/upper);
fprintf('%d %3.6f %3.4f %3.4f %3.8f%%\n',iter,lower,upper,xr,err*100);
end
end
end
Accepted Answer
James Tursa
on 29 Mar 2019
You need to move your err initialization inside your loop. I.e., these lines need to move:
iter=0;
err=1;
Also, you need to index into your e vector. E.g., this line
while(err>e(i)) % <-- e changed to e(i)
0 Comments
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements 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!