MATLAB: Index exceeds the number of array elements in while loop

indexMATLABwhile loop

I ve been trying to create a Fibonacci Sequence in which ratio of the adjacent values converge to 0.001. Here is the code I've written so far:
clc
clear
x = input('Please enter the first number in the series:');
y = input('Please enter the second number in the series:');
s(1) = x;
s(2) = y;
k = 3;
while abs(s(k)./s(k-1) – s(k-1)./s(k-2))>0.001
s(k) = s(k-1) + s(k-2)
k = k+1;
end
disp(s)
But when I run the code, it says; Index exceeds the number of array elements (2)
Error is on the eighth line.

Best Answer

Hi,
I just shuffled the code a bit. Check this:
clc
clear
x = input('Please enter the first number in the series:');
y = input('Please enter the second number in the series:');
s(1) = x;
s(2) = y;
k = 3;
Cond =1; % intialize the condition
while Cond > 0.001
s(k) = s(k-1) + s(k-2);
Cond = abs(s(k)/s(k-1) - s(k-1)/s(k-2));
k = k+1;
end
disp(s)