Need help with this Matlab script question? For loop!!

1 vue (au cours des 30 derniers jours)
Dylan Flores
Dylan Flores le 29 Juil 2014
Modifié(e) : Dylan Flores le 29 Juil 2014
I keep getting this error 'Attempted to access x(3); index out of bounds because numel(x)=2.' It's really frustrating!!!

Réponse acceptée

ES
ES le 29 Juil 2014
You have to define x(3) as well (It should be 2 right ?), and then run the loop from x=3 and change the order of statements inside the while loop, because you set x(k) and then increment k. so for the new incremented k, x(k) will not be defined yet.
Please check:
%%Determining the golden ratio in a fibonacci sequence clear,clc % Defining the first two elements in the sequence x(1) = 1;
x(2) = 1;
x(3) = 2;
k = 3;
while (abs(x(k)./x(k-1) - x(k-1)./x(k-2))>0.001)
k = k+1;
x(k) = x(k-1) + x(k-2);
end

Plus de réponses (1)

Robert Cumming
Robert Cumming le 29 Juil 2014
Modifié(e) : Robert Cumming le 29 Juil 2014
It the start of your while loop the condition includes a check on x(3), hence why you get the error.
edit: you could fix it this way:
while true
x(k) = x(k-1) + x(k-2);
k = k+1;
if (abs(x(k)./x(k-1) - x(k-1)./x(k-2))>0.001)
break
end
end

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by