MATLAB: Can someone look over the newton’s method script and see if it looks ok

loopnewton's methodscript

for F(X)=x^3-2x and F'(x)=3x^2-2 with initial guess of x=1
if true
% code
endx = 1;
Tol = 0.0000001;
count = 0;
dx=1;
f=-1;
fprintf('step x dx f(x)\n')
fprintf('---- ----------- --------- ----------\n')
fprintf('%3i %12.8f %12.8f %12.8f\n',count,x,dx,f)
xVec=x;fVec=f;
while (dx > Tol || abs(f)>Tol)
count = count + 1;
fprime = 3*x^2 - 2;
xnew = x - (f/fprime);
dx=abs(x-xnew);
x = xnew;
f = x^3 - 2*x;
fprintf('%3i %12.8f %12.8f %12.8f\n',count,x,dx,f)
end

Best Answer

Several obvious things.
First of all, you never evaluate f to start the method out. Yes, since you know the function f AND the starting value, f(1) = -1, so your code looks like it will work since you hard coded f initially as -1, but it is poor coding style anyway.
Second, I strongly suggest you learn not to hard code in your functions, like f(x) and f'(x). Learn to set up such a function up front, so you could use your code to solve a more general problem. For example, you could set up function handles up front...
f_x = @(x) x.^3 - 2*x;
fp_x = @(x) 3*x.^2 - 2;
I'd also suggest putting in a test for a MaxFunEvals or MaxIterations to prevent some problems. You also use the same Tol parameter for both a test on dx and on abs(f). While that might work on some problems, it is a bad idea in general.