Hi @Cesar,
Let me address your comment:” not sure why I'm getting this error, any help will be appreciated. thanks"
The error you're encountering is due to a syntax issue with a misplaced end statement in your code that's creating a variable scope problem.
The Root Cause: In your code, you have a stray end statement that prematurely terminates your function before the while loop executes:
found = false; pow = -1; E = []; % expansion log [pow, a, b, f(a), f(b)] end % ← This end statement terminates the function here while pow < dmaxpow % MATLAB throws error: pow is now out of scope
The Fix: Simply remove the misplaced end statement on line 6:
function topic4_p2_expand_then_bisect() f = @(x) exp(-x) - x; x0 = 0; d = 0.1; dmaxpow = 6; % expand symmetrically until sign change or limit found = false; pow = -1; E = []; % expansion log [pow, a, b, f(a), f(b)] % Remove the misplaced 'end' here while pow < dmaxpow pow = pow + 1; a = x0 - d; b = x0 + d; fa = f(a); fb = f(b); E(end+1,:) = [pow, a, b, fa, fb]; if fa*fb <= 0, found = true; break; end d = 2*d; end % ... rest of your code remains unchanged
Why This Happens: When MATLAB encounters that premature end, it thinks your function is complete. The subsequent while loop appears to be outside any function scope, so the variable pow (defined inside the now-terminated function) becomes unrecognized.
This should resolve your error completely. Your expand-then-bisect algorithm implementation is well-structured otherwise.