Undefined function or variable 'r', but I am confident I defined it
7 views (last 30 days)
I am trying to use the bisection method to evaluate a function.
function [r,iter] = bisect(xl,xu,es,imax)%inputs are: left x value, right x value, stopping criterion, maximum iterations
iter = 0;
while (abs(xu-xl)>=es) %runs a nonstop loop under specified conditions
xr = (xl+xu)/2; %midpoint of xl and xu values to approximate root
xrold = xr;
iter = iter+1;
ea=abs((xr-xrold)/xr)*100; %calculate approximate error
test = feval(f,xl)*feval(f,xr); %test if functions have opposite signs
if test < 0
xu = xr;
elseif test > 0
xl = xr;
ea = 0;
if ea < es || iter >= imax %if approx. error is less than stopping criterion, or number of iterations is greater than or equal to maximum amount of iterations, stop loop
r = xr;
However, when I run the function with inputs, it returns "Undefined function or variable 'r'". As a test to see what was wrong, I evaluated the line
it says that xl is undefined, even though I put in a value for it upon running the function through my command line. Can anyone help me figure out what's making my code respond with this, and what I should do to avoid this problem? Thank you.
Geoff Hayes on 22 Feb 2018
Steelierelk - I suspect that the
"Undefined function or variable 'r'"
corresponds to the
line. If this is true, then this is because whatever inputs you have entered are such that the while loop condition
evaluates to false...and so the r variable never gets set. I would set a breakpoint at this line (the while condition) and verify that the values you have passed into this function make sense given the condition.
It is also good practice to assign default values to output variables so that at least something is assigned to them.
And, what do you mean by you evaluated the line xr=(xl+xu)/2. When did you evaluate this? After you had run the function (in which case the variables would be out of scope and so be undefined)? Or were you stepping through the code with the debugger?
Roger Stafford on 22 Feb 2018
In your code you set xrold equal to xr and compute ea:
which not surprisingly gives ea a zero value. This guarantees that your later test ea < es for es a positive number will produce a break on the first trip through the while loop. This means that the line r = xr never get executed and hence r is undefined.