I want to produce the nth term of the Fibonacci Sequence, however I keep getting the error, "Attempted to access fibonacci(4); index out of bounds because numel(fibonacci)=3." So far I have the following code:
function f = fibonacci(n)
fibonacci(1) = 1;
fibonacci(2) = 1;
fibonacci(3) = 2;
i = 3;
n = 1000000000000;
while (i <= n)
f = fibonacci(i-1) + fibonacci(i-2);
i = i + 1;
end
end

1 件のコメント

LUIGI ALESSANDER HUAMAN TORRES
LUIGI ALESSANDER HUAMAN TORRES 2020 年 10 月 25 日
function f = fibonacci(nmax)
f=zeros(nmax,1);
f(1) = 0;
f(2) = 1;
f(3) = 1;
i = 3;
while (i <= nmax)
f(i) =f(i-1) + f(i-2);
i = i + 1;
end
end

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

 採用された回答

James Tursa
James Tursa 2015 年 3 月 9 日
編集済み: James Tursa 2015 年 3 月 9 日

0 投票

You don't assign your iterative result to the fibonacci array. E.g.:
fibonacci(i) = fibonacci(i-1) + fibonacci(i-2);
HOWEVER, this formulation is increasing the size of the fibonacci variable in a loop, which can have severe timing consequences unless the parser saves you. I would advise that you reformulate your code to pre-allocate this array, or since you don't need to save the array work with only three values at a time ((i-2)'th, (i-1)'th, and i'th) using only three variables (e.g., fibonacci2, fibonacci1, fibonacci0).

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by