Loop with Bisection Method Error (for may not be aligned etc.)

13 visualizaciones (últimos 30 días)
Josh
Josh el 12 de Feb. de 2016
Respondida: Geoff Hayes el 12 de Feb. de 2016
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

Respuestas (1)

Geoff Hayes
Geoff Hayes el 12 de Feb. de 2016
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?

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by