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))

Antworten (2)

Blair Ebeling
Blair Ebeling am 15 Okt. 2015

0 Stimmen

The code showed up weird, this is the 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))
Walter Roberson
Walter Roberson am 15 Okt. 2015

0 Stimmen

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)

Kategorien

Tags

Gefragt:

am 15 Okt. 2015

Beantwortet:

am 15 Okt. 2015

Community Treasure Hunt

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

Start Hunting!

Translated by