MATLAB: I’m getting “Index exceeds array bounds.” and I’m not sure how to fix it.

fibonacciloopswhile loops

Here's the problem.
One interesting property of a Fibonacci sequence is that the ratio of the values of adjacent members of the sequence approaches a number called “the golden ratio” or Φ (phi). Create a program that accepts the first two numbers of a Fibonacci sequence as user input, then calculates additional values in the sequence until the ratio of adjacent values converges to within 0.001. You can do this in a while loop by comparing the ratio of element k to element k – 1, and the ratio of element k – 1 to element k – 2. If you call your sequence x, then the code for the while statement is
whileabs(x(k)/x(k1) x(k1)/x(k2))+0.001
This is my code.
%9.8
first_input = input('Enter the first number ');
second_input = input('Enter the second number ');
x(1)=first_input;
x(2)=second_input;
k=3;
while abs((x(k)/x(k-1)) - (x(k-1)/x(k-2)))>0.001
x(k)=x(k-2)+x(k-1);
k=k+1;
end
disp(x)

Best Answer

You need to calculate x(3) from x(1) and x(2) before you start the while loop.