Loop with Bisection Method Error (for may not be aligned etc.)
13 次查看(过去 30 天)
显示 更早的评论
I have a bisection method function that is running inside a loop to generate solutions for multiple values p. However, I'm getting an error that says "FOR may not be aligned with its matching end" yet there are the correct number of end statements for the loops in my code. What can I do to solve this?
k = 0.05;
p = 1:.2:4;
%preallocate solution vectors
x1 = zeros(length(p),1);
approx_err1 = zeros(length(p),1);
iter = zeros(length(p),1);
for p = 1:.2:4
fun = @x x/(1-x) * sqrt((2p)/(2+x)) - k;
es = 1*10^-4; %stopping tolerance
xl = 0.01; xu = 0.1; xroot = xl; %initial guesses
%bisection function
for iter 1:50
xr_old = xroot;
xroot = (xl + xu)/2;
ea = (xroot - xr_old)/xroot;
test = fun(xl) * fun(xroot);
if abs(ea) <= es, break, end
if test < 0
xu = xroot;
elseif test > 0
xl = xroot;
else
ea = 0; %test = 0, means found exact root
end
end
%end bisection function
x1 (p,:) = xroot;
approx_err1 (p,:) = ea;
iter (p,:) = iter;
end
0 个评论
回答(1 个)
Geoff Hayes
2016-2-12
Josh - FOR may not be aligned with its matching end is a warning only and can be ignored for the moment. In fact, once you resolve the errors, this warning message will disappear. With line
fun = @x x/(1-x) * sqrt((2p)/(2+x)) - k;
there is a Parse error at x: usage might be invalid MATLAB syntax. For anonymous functions, you need to wrap the input variable(s) in parentheses like
fun = @(x) x/(1-x) * sqrt((2p)/(2+x)) - k;
This will lead to another error message invalid syntax at p. What is the intent here? Do you wish to multiply p by 2 or divide or ..? You must supply the correct operator.
Once that has been corrected, there will be another parse error at the line
for iter 1:50
You are missing an equals sign to indicate which values the indexing variable iter is meant to take on
for iter=1:50
And that is it. The warning message disappears and you should be good to execute the code....except for the
Subscript indices must either be real positive integers or logicals.
Error in xxxx (line 27)
x1 (p,:) = root;
which is telling you that your p is not a real positive integer. In this case it is a double since p is the indexing variable of the outer for loop
for p = 1:.2:4
What are you trying to assign to x1 and why are you trying to use p? What is intended here?
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!