Fibonacci sequence for loop

3 ビュー (過去 30 日間)
Leonardo Aldeghi
Leonardo Aldeghi 2019 年 10 月 7 日
コメント済み: Jos (10584) 2019 年 10 月 7 日
Hey guys, I'm trying to write in Matlab Grader a function that returns a vector containing all elements of the Fibonacci sequence that are smaller or equal than m.
This is my code:
function fibonacciValue=fibonacciValue(m)
fibonacciValue(1) = 1;
fibonacciValue(2) = 1;
n=3;
while fibonacciValue(n-1) < m;
fibonacciValue(n) = fibonacciValue(n-1)+fibonacciValue(n-2);
n=n+1;
end
The goal is to display the sequence up to the number equal to m; e.g. fibonacciValue(3)=[1,1,2,3] and fibonacciValue(10)=[1,1,2,3,5,8].
The problem is that it works for m=3, but not for higher numbers.
fibonacciValue(3)
Schermata 2019-10-07 alle 11.34.08.png
fibonacciValue(10)
Schermata 2019-10-07 alle 11.34.22.png
Does anybody knows how to fix this?
Thanks!!

採用された回答

Stephen23
Stephen23 2019 年 10 月 7 日
編集済み: Stephen23 2019 年 10 月 7 日
Your while loop does not exit when you probably think it should...
Actually you will get the correct answer for m=3, 5, 8, 13, etc., as then the final loop iteration will generate exactly that value. But what happens when m is not one of the numbers in the fibonacci sequence? Then your loop will calculate one more iteration and return a vector one element longer than you want.
One simple solution is to use <= and remove the last vector element:
m = 10;
V = [1,1];
while V(end)<=m; % less-than or equal
V(end+1) = sum(V(end-1:end));
end
V = V(1:end-1) % you need this!
  2 件のコメント
Leonardo Aldeghi
Leonardo Aldeghi 2019 年 10 月 7 日
function fibonacciValue=fibonacciValue(m)
fibonacciValue(1) = 1;
fibonacciValue(2) = 1;
fibonacciValue = [1,1];
while fibonacciValue(end)<=m; % less-than or equal
fibonacciValue(end+1) = sum(fibonacciValue(end-1:end));
end
fibonacciValue = fibonacciValue(1:end-1); % you need
I put your code in and worked perfectly! Thanks!!
Jos (10584)
Jos (10584) 2019 年 10 月 7 日
Alternatively, you can take the n-2 value into account
while fibonacciValue(n-1)+fibonacciValue(n-2) < m
% ...
and not have to remove the last element

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

その他の回答 (0 件)

カテゴリ

Help Center および 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