Error in code: attempted to access x(0)
古いコメントを表示
I am writing a code for fixed point iteration. Whenever I try to run the code, I get an error that says:
Attempted to access x(0); index must be a positive integer or logical.
It says the error is with x(0)=10000000.
This is my code:
g(x) = (1/2)*cos(x);
p = input('What is the initial guess \n');
x(0)=10000000
tol = input('What is the relative error tolerance \n');
imax = input('What is the iteration limit \n');
i = 0
while abs(x(1)-x(0)) <= (x(1)*tol) && i > imax
x(0) = x(1)
x(1) = (1/2)*cos(x(0))
i = i+1
end
fprintf('x1 is %g \n',x(1))
回答 (2 件)
Blair Ebeling
2015 年 10 月 15 日
Walter Roberson
2015 年 10 月 15 日
0 投票
MATLAB has never supported indexing at 0. x(0) has always been an error in MATLAB. The first element of array or vector x is x(1)
In other words, add 1 to all of your subscript references. x(0+1), x(1+1)
There is no point in using a vector in the code your show: you might as well use variables named x0 and x1 . A vector would be useful if you were referring to x(i) .
Note by the way that your code refers to x(1) before having assigned anything to x(1)
カテゴリ
ヘルプ センター および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!