MATLAB: How to update the values in this loop

arrayloops

I created a simple bisection method program. But im trying to store my values in an array as below. However everytime i run it, it only updates the first element of the array, and doesnt update each other element in the array after each loop:
function [m] = BisectionMethodTEST(func,x0,x1)
% x0 is the left endpoint
% x1 is the right endpoint
err = input('Enter the error: ');
TOL = input('Enter total iterations: ');
format compact
y = zeros(1,TOL);
m = zeros(1,TOL);
p = zeros(1,TOL);
flog = 0; %Break out of nested loops
for i = 1:(TOL - 1)
while abs(x1 - x0) > err
m(i+1) = m(i) + (x0 + ((x1 - x0)/2))
y(i+1) = y(i) + func(m(i+1))
if y(i+1) < 0
x0 = m(i+1)
else
x1 = m(i+1)
end
if p(i+1) > TOL
flog = 1;
break
end
end
p(i+1) = p(i) + 1
if flog == 1 %this statement breaks out of nested loops
break
end
end
end

Best Answer

Inside the "for" you have
while abs(x1 - x0) > err
but you do not change x1, x0, or err after the end of the "while", so they are going to be whatever they were left at in the next iteration of the for loop. If the loop did not exit with flog == 1 then the condition on the while will be immediately false; if the loop did exit with flog == 1 then the "for" will exit. Either way, you will not enter the body of the while loop twice.