需要有关"Attempted to access.... ; index out of bounds because numel(...)=1"错误的帮助



我需要在 Matlab 上编写一个牛顿方法代码并通过此处进行处理。但是当我尝试使用它时,它在计算几次后给出了此错误:

试图访问 df(8);索引越界,因为数字(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 

我该怎么办?

那是因为

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

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

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

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

顺便问一下,为什么不使用中心差异?

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

以相同的成本,您将获得一个数量级的精度......对我来说似乎很划算:)

相关内容

最新更新