フィルターのクリア

Index exceeds the number of array elements in while loop

1 回表示 (過去 30 日間)
Kaan Uçar
Kaan Uçar 2019 年 3 月 25 日
コメント済み: Kaan Uçar 2019 年 4 月 13 日
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.
  3 件のコメント
Kaan Uçar
Kaan Uçar 2019 年 3 月 25 日
I defined s(3) as x + y and and still get the error. This time in parantheses it says 3 instead of 2.
Kevin Phung
Kevin Phung 2019 年 3 月 25 日
編集済み: Kevin Phung 2019 年 3 月 25 日
ok, and where is that in your code? What is see is that you've set s(1) and s(2) to be the user input.
Youve made k a constant 3, and your while loop CONDITION:
while abs(s(k)./s(k-1) - s(k-1)./s(k-2))>0.001
starts with s(k) which is s(3), and that does not exist.

サインインしてコメントする。

採用された回答

Raghunandan V
Raghunandan V 2019 年 3 月 26 日
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)
  1 件のコメント
Kaan Uçar
Kaan Uçar 2019 年 4 月 13 日
Sorry for the late response. I got the problem fixed. Thank you for your helps.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by