On 4/19/2012 9:51 PM, James wrote:
> Hey I've never used MATLAB before and I am having trouble getting my simple Newton's method code to work. Here's what I have so far:
>
> clear all
> clc
> x = zeros(6,1);
> x(1) = 3.0;
> f = x.^21;
> df = 2.*x;
> for n = 1:6
> x(n+1) = x(n)  f(n)/df(n)
> end
>
> After two iterations, all of my x values go to Inf. Maybe I've just
>been staring at this for too long, but its too annoying to quit. Thanks.

f = @(x) x^21;
df = @(x) 2*x;
x = .1; %initial guess
keep_trying = true;
k = 0; %counter
while keep_trying
x = x  f(x)/df(x);
k = k+1;
if abs(f(x)) < 0.001 %change tolerance as needed
keep_trying = false;
end
if k>15
keep_trying = false; %give up !
end
end
%assume we found a root for now
fprintf('root found at %f, after %d iterations\n',x,k)
%compare
fzero(f,.1)

Nasser
