Fibonacci.m for Fibonacci Series

19 ビュー (過去 30 日間)
Siyi Wang
Siyi Wang 2020 年 6 月 5 日
コメント済み: Siyi Wang 2020 年 6 月 6 日
Here is a .m file what I made for Fibonacci Series:
function F = Fibonacci(n)
%Fibonacci Series: Calculate the nth term
%The Fibonacci numbers are the sequence 0, 1, 1, 2, 3, 5, 8, 13, 21….
%Given that the first two numbers are 0 and 1, the nth Fibonacci number is
%Fn = Fn–1 + Fn–2.
%Applying this formula repeatedly generates the Fibonacci numbers.
F(1) = 0;
F(2) = 1;
i = 3;
while i <= n
F(i) = F(i-1)+F(i-2);
i = i+1;
end
F = F(n);
end
If I input n is single number such as:
n=10;
Fibonacci(n)
It can give me the correct answer:
ans = 34
However, if I input n is an array, such as:
n=1:10;
Fibonacci(n)
It gives the error warning:
Index exceeds the number of array elements (2).
Error in Fibonacci (line 15)
F = F(n);
I just wonder why it occurs this information?

採用された回答

James Tursa
James Tursa 2020 年 6 月 5 日
編集済み: James Tursa 2020 年 6 月 5 日
You function is not vectorized ... that is, it is not written to handle anything other than a scalar input. As written, you would need to call your function in a loop. E.g.,
n=1:10;
for k=1:numel(n)
F(k) = Fibonacci(n(k));
end
The alternative would be to rewrite your function so that it can handle non-scalar inputs. E.g., suppose you did this:
m = max(n);
while i <= m
  1 件のコメント
Siyi Wang
Siyi Wang 2020 年 6 月 6 日
Great! It solves my problem. Very consise, clear, and helpful. I prefer the second code, which sounds better to modify the funtion. Thanks.

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

その他の回答 (1 件)

the cyclist
the cyclist 2020 年 6 月 5 日
編集済み: the cyclist 2020 年 6 月 5 日
This code is not really written to handle anything but a scalar input. Consider this line in the code:
while i <= n
What would you expect it to do as it tries to evaluate this:
while 3 <= 1:10
?
It's certainly not what you intend, which would be some kind of parallel ("vectorized") version.
Instead, it's going to skip past that while loop because it is not true for all elements of the vector, and then try to evaluate
F = F(1:10)
which gives the error you see.
  1 件のコメント
Siyi Wang
Siyi Wang 2020 年 6 月 6 日
Thanks! As a beginner for me, Very helpful!

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

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by