【问题标题】:Need help on "Attempted to access.... ; index out of bounds because numel(...)=1" error需要有关“尝试访问....;索引超出范围,因为 numel(...)=1”错误的帮助
【发布时间】:2013-10-21 13:30:45
【问题描述】:

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

尝试访问 df(8);索引超出范围,因为 数字(df)=1。

newton 方法中的错误(第 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 

我该怎么办?

【问题讨论】:

    标签: matlab


    【解决方案1】:

    那是因为

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

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

    为了能够计算任何tidf = df(ti) 的值,您应该将其定义为anonymous function

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

    顺便说一句,为什么不使用central differences

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

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

    【讨论】:

    • 谢谢!它解决了问题,但我现在又遇到了另一个错误:我该怎么办? Error using fprintf Invalid file identifier. Use fopen to generate a valid file identifier.Error in newtonmethod (line 15) fprintf(tz,'counter=',counter )
    • @Profhero:是的,请阅读documentation。命令fprintf 将数据写入文本文件。仅当您提供文件 ID 12 时,它才会写入 MATLAB 等效的 stdout(命令窗口中的普通文本)或 stderr(命令窗口中的错误文本)。省略文件 ID 时默认为 stdout
    • 谢谢,我只是想将结果发送到命令窗口,但看起来我还有很长的路要学习 matlab。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多