While loop doesn't continue looping!

1 次查看(过去 30 天)
Hey everyone,
In my code for estimating the root using bisection method, while loop only outputs one iteration! yy is user defined function for which the root will be estimated, Xl is the lower bound of the interval (user-defined), Xu is the upper bound of the interval (user-defined), imax is the max number of iterations, I use a function fun to convert the symbolic function into numerical
function [iter, Xr, ea] = Bisect(yy, Xl ,Xu ,es ,imax, iter)
while iter <= imax || ea <= es
if (fun(yy,Xl) * fun(yy,Xu)) < 0 %Verify that the interval [Xl,Xu] contains at least one root by examining the sign
Xr = (Xl + Xu)/2;
if (fun(yy,Xr) * fun(yy,Xl)) < 0
ea = abs((Xr - Xu)/Xr)*100;
Xu = Xr;
else
ea = abs((Xr - Xl)/Xr)*100;
Xl = Xr;
end
break
elseif fun(yy,Xl) == 0
Xr = Xl;
ea = 0;
break
elseif fun(yy,Xu) == 0
Xr = Xu;
ea = 0;
break
elseif (fun(yy,Xl)*fun(yy,Xu)) > 0
disp('ERROR!! Please specify another upper and lower bounds for the interval on which a root might exist.')
break
end
end
iter = iter + 1; %Update the number of iterations

回答(1 个)

Naty S
Naty S 2013-2-26
Use continue instead of break. But i don't think you really need all those breaks or continues. Try without them. and in the elseif, you should change it from elseif fun(yy,xu)==0 to elseif fun(yy,xu)<Epsilon

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by