Recursive Function with two Base Cases

Hi
Let the Lucas Numbers be defined as follows:
1 for n = 1
3 for n = 2
L_n = L_(n-1) + L_(n-2) for n >= 3
Why doesn't my code work? Here is the code:
function a = lucas(N)
N = input('please enter an integer:')
if N == 1
a = 1;
elseif N == 2
a = 3;
elseif
a = lucas(N-1)+ lucas(N-2)
end
disp(N)
end
thanks!

回答 (1 件)

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 2 月 19 日
編集済み: Azzi Abdelmalek 2013 年 2 月 19 日

0 投票

It's not elseif use else
Also you are using a function with input argument N, why in your function you added:
N = input('please enter an integer:')
What you should do is:
function a = lucas(N)
if N == 1
a = 1;
elseif N == 2
a = 3;
else
a = lucas(N-1)+ lucas(N-2)
end
disp(N)
And in windows command
N = input('please enter an integer:')
a=lucas(N)

5 件のコメント

MiauMiau
MiauMiau 2013 年 2 月 19 日
Unfortunately, that answer doesn't help
Azzi Abdelmalek
Azzi Abdelmalek 2013 年 2 月 19 日
You should try it.
MiauMiau
MiauMiau 2013 年 2 月 19 日
編集済み: Azzi Abdelmalek 2013 年 2 月 19 日
although you have edited your answer now,
  1. the programms output is not according to the rules defined above. N = 4 for instance should give an output of 7.
  2. the program stays in an infinte loop.
Azzi Abdelmalek
Azzi Abdelmalek 2013 年 2 月 19 日
編集済み: Azzi Abdelmalek 2013 年 2 月 19 日
I forget to remove , input from your function. It gives 7 for N=4
save this function
function a = lucas(N)
if N == 1
a = 1;
elseif N == 2
a = 3;
else
a = lucas(N-1)+ lucas(N-2)
end
disp(N)
in windows command type
lucas(4)
MiauMiau
MiauMiau 2013 年 2 月 19 日
now it works, thanks!

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

カテゴリ

ヘルプ センター および File ExchangeWaveform Design and Signal Synthesis についてさらに検索

タグ

質問済み:

2013 年 2 月 19 日

Community Treasure Hunt

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

Start Hunting!

Translated by