我需要在Matlab上编写牛顿法代码,然后在这里进行处理。但是,当我尝试使用它时,经过几次计算,它会产生这样的错误:
试图访问df(8);索引超出界限,因为numel(df)=1.
牛顿法中的误差(第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 我该怎么办?
发布于 2013-10-21 05:30:45
那是因为
df = (f(ti+h)-f(ti))/h; 计算单个值(在ti = 10处),而不是定义函数。
若要计算任何df = df(ti)的值,应将其定义为匿名函数
df = @(ti) ((f(ti+h)-f(ti))/h); 顺便问一下,为什么不使用中心差异呢?
df = @(ti) (f(ti+h)-f(ti-h))/2/h;对于同样的成本,您将得到一个数量级的accuracy...seems,这对我来说是一笔不错的交易:)
https://stackoverflow.com/questions/19486807
复制相似问题