MATLAB: Newton Raphson Method – how to return errors of each iteration in arrays

newton raphson method

How do I get this function to return 2 arrays – X and Y.
I have developed a function that implements the Newton-Raphson Method and calculates the root (z) of a given function with an inicial guees (x0), the stop criteria(TolX) and MaxIter. But now want it to return also 2 arrays – X and Y :
where | ek | = | m – xk | is the absolute error of iteration xk and m = 0.658302191121686.
The code I have so far is:
function [z, fz, iter, x, y] = quasinewton(f, x0, TolX, MaxIter)
% f = (1^(-2*x))*(2*sin(4*x)+cos(4*x))-0.1 TolX = 1e-12
delta = 1*10^(-4);
m = 0.658302191121686;
iter = zeros(MaxIter+1,1); %Pre-allocates memory for iter vector
iter(1) = x0; %x0 = 0.5
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
e(k) = m – iter(k); %% line added for arrays x and y
y = log(abs(e(k))); %% line added for arrays x and y
x = log(abs(e(k-1))); %% line added for arrays x and y
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);
fprintf('The best in %d iterations is f = %f at x = %f \n', k, f(z), z);
end
Can you tell me what is wrong with the code, please? I've just started matlab (1 week ago..)

Best Answer

I would pull the calculations outside the loop.
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
e = abs(m - iter);
y = log(e(2:end));
x = log(e(1:end-1));