MATLAB: How to correct endless while loop when implementing secant method as a function

matlab functionwhile loop

When I attempt to run my function, it says that only one iteration is performed and it gives the value of x for the first iteration. Then the function runs endlessly until I pause it. I'm new to coding. Can anyone point out where I'm going wrong?
if true
% code
end
function [x,k] = Steele_Secant(f,x0,x1,tol,N)
%This program will find the root of a function using the secant method.
%Initialize counter
k = 0;
%secant method
x = x1-(f(x1)*(x1-x0))/(f(x1)-f(x0));
while (abs((x-x1))>tol)
x1=x;
x0=x1;
k=k+1;
%continue iterations until value of x is within tolerance
x = x1-(f(x1)*(x1-x0))/(f(x1)-f(x0));
if (k==N);
fprintf('%i iterations reached',k)
break
end
%display number of iterations and x value once root is found
fprintf('%i iterations were performed \n', k)
fprintf('%.2f is the root of the function \n', x)
end
end

Best Answer

You're passing in 1 for N.
You're trying to do exactly N iterations so for that you should use a for loop, not a while loop. Anyway, step through it with the debugger and you'll discover why it doesn't stop. Do you know how to use the debugger? If not, you absolutely must learn. Debugging through a long, time consuming exchange on Answers is no way to debug.
Related Question