Fibonacci function displaying issues

I created a function for a fibonacci number. I want it to display the largest fibonacci number that is less than or equal to the input. I currently have it set up to run and it will display the last number in the series. Any suggestions as to getting it to display the largest number less than or equal to n?
function f=lastfibonacci(n)
% Returns the largest fibonacci number that is less than or equal to n.
if n<=1;
f=1;
else
f=(lastfibonacci(n-1)+lastfibonacci(n-2));
end
end
Wanting:
Ex.: lastfibonacci(7)
ans= 5

 採用された回答

Matt Fig
Matt Fig 2012 年 10 月 19 日

0 投票

If you choose to use recursion, you will have quite some time with this. I think it is better to use iteration, myself.
function F3 = lastfibonacci(n)
% Help, and need to check for n<1.
F1 = 1;
F2 = 1;
while F2<=n
F3 = F2;
F2 = F2 + F1; % The Fib number.
F1 = F3;
end

その他の回答 (1 件)

Image Analyst
Image Analyst 2012 年 10 月 19 日

0 投票

Ashlee, I suggest you add this line at the beginning of the function to help you debug it:
fprintf('n = %d\n', n);

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

質問済み:

2012 年 10 月 18 日

Community Treasure Hunt

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

Start Hunting!

Translated by