Error in code: attempted to access x(0)
Afficher commentaires plus anciens
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))
Réponses (2)
Blair Ebeling
le 15 Oct 2015
Walter Roberson
le 15 Oct 2015
0 votes
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)
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!