Secant method error, "subscript indicies must be real or positive integers"

12 ビュー (過去 30 日間)
Harjot Purewal
Harjot Purewal 2016 年 10 月 31 日
コメント済み: Harjot Purewal 2016 年 10 月 31 日
here is my code, I get the error at line 10 at x(n+1) = x(n) - .... I have also attached it as an .m file
Matlab code
y = @(x) x.^3 - .3;
x(1) = .01;
x(2) = .02;
tol = 1e-5;
eps = 500;
iteration_secant = 0;
n = 1;
while abs(eps) > tol
x(n+1) = x(n) - ((y(x(n))*(x(n)-x(n-1))/(y(x(n))-y(x(n-1)))));
iteration_secant = iteration_secant +1;
eps = ((x(n+1) - x(n))/x(n));
n=n+1;
if n > 100
break
end
end
x(n+1)

回答 (1 件)

Roger Stafford
Roger Stafford 2016 年 10 月 31 日
You enter the while loop with n = 1. This means that x(n-1) would have an index value of zero. This is a no-no in Matlab. You will have to revise your code to avoid this.
  1 件のコメント
Harjot Purewal
Harjot Purewal 2016 年 10 月 31 日
I have changed it to n=2; from n=1; however I still get the same error and for some reason the value of n is still 1 when I run my code any idea of why this is the case?

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeEntering Commands についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by