1

I needed to write a Newton method code on Matlab and processed through here. But when I try to use it, it gives this error after calculating a few times:

Attempted to access df(8); index out of bounds because numel(df)=1.

Error in newtonmethod (line 11) tz=ti-(f(ti)/df(ti));

 function newtonmethod(f)
ti = 10;
tz = 8;
abstol = 0.0001;
counter = 0;
h=0.1;
df=((f(ti+h)-f(ti))/h);
while (abs(ti-tz)>abstol)
    ti=tz;
    tz=ti-(f(ti)/df(ti));
    counter=counter+1;
end
    ti=tz;
    fprintf(tz,'counter=',counter )
end 

What should I do?

4

1 回答 1

0

那是因为

df = (f(ti+h)-f(ti))/h; 

计算单个值(at ti = 10),而不是定义函数。

为了能够计算df = df(ti)any的值ti,您应该将其定义为匿名函数

df = @(ti) ((f(ti+h)-f(ti))/h); 

顺便说一句,为什么不使用中心差异

df = @(ti) (f(ti+h)-f(ti-h))/2/h;

以相同的成本,您将获得更高数量级的准确性……对我来说似乎很划算:)

于 2013-10-21T05:30:45.713 回答