I'm getting "Index exceeds array bounds." and I'm not sure how to fix it.
3 次查看(过去 30 天)
显示 更早的评论
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(k−1) − x(k−1)/x(k−2))+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)
0 个评论
采纳的回答
Walter Roberson
2018-5-16
You need to calculate x(3) from x(1) and x(2) before you start the while loop.
3 个评论
Walter Roberson
2018-5-16
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!