I'm getting "Index exceeds array bounds." and I'm not sure how to fix it.

4 views (last 30 days)
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)

Accepted Answer

Walter Roberson
Walter Roberson on 16 May 2018
You need to calculate x(3) from x(1) and x(2) before you start the while loop.
  3 Comments
Walter Roberson
Walter Roberson on 16 May 2018
When k = 3, you assign to x(k) which is x(3), which already has a value. Then you increment k to 4 and try to access x(k) which is x(4) which has not been defined.
Hint: move the increment of k to before the assignment.

Sign in to comment.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!