MATLAB: Alternative Newton-Method using for-loop

for loopnewton raphson method

I have a task that requires me to create an alternative Newton-Raphson Method – not using a derivative function – described by:
where the delta value is given and its very close to 0. The input data should be a function f, the initial approach x0, the required minimum accuracy TolX for the stop criterion | (xk+1 —xk) / xk+1 | and the maximum number of iterations MaxIter. The results should be the approximation of the root z, the value of the function in the root fz and a vector containing iter iterations.
This is the code I have so far:
function [z, fz, iter] = quasinewton(f, x0, TolX, MaxIter)
% f = x^3-x^2-x+1 TolX = 1e-2
delta = 1*10^(-5);
iter = zeros(MaxIter+1,1); %Pre-allocates memory for iter vector
iter(1) = x0; %x0 = -0.2
for k = 1:MaxIter
fz = feval(f, iter(k));
dfdx = fz / (feval(f, iter(k) + delta) – fz);
iter(k+1) = iter(k) – (dfdx * delta); %Calculates new iteration
err = (iter(k+1)-iter(k))/iter(k+1); %calculates the error of sucessive iterations
fz = feval(f, iter(k+1));
if abs(err) < TolX, break; end
end
z = iter(k+1);
if k == MaxIter
fprintf('The best in %d iterations\n', MaxIter)
end
It keeps giving me the wrong iterations and instead of converging to 0 it increases iteration after iteration. I really don't understand what could be wrong. I'm new in Matlab. Any suggestions?

Best Answer

It works for me ok using the function f = x^3-x^2-x+1 and initial guess x0 = -2. However, replace
if k == MaxIter
fprintf('The best in %d iterations\n', MaxIter)
end
by
fprintf('The best in %d iterations is f = %f at x = %f \n', k, f(z), z)