Write a recursive function called fibor

Hello, I got a question as a below figure
My approach is as the following code:
function output = fibor(n)
a = 0; b = 1;
output = recursive_tail(n,a,b);
end
function out = recursive_tail(n,a,b)
if n == 0
out = a;
elseif n == 1
out = b;
else
out = [b recursive_tail(n-1,b,a+b)];
end
end
The result is good (3/4 test cases), but the last one, the Grade External Tool does not eccept it as a recursive solution, I guest that because I call back the function "recursive_tail" instead of "fibor". Could you guys check the code for me, or any suggestions for the solution? I would appreciate it so much. Thank you guys.

2 件のコメント

Jan
Jan 2022 年 3 月 19 日
"the Grade External Tool does not eccept it as a recursive solution" - do you get a corresponding message? If so, sharing it with the readers is a good idea. Otherwise it could be possible, that it is only a guess, what the problem is.
Duong Nguyen
Duong Nguyen 2022 年 3 月 19 日
編集済み: Duong Nguyen 2022 年 3 月 19 日
My mistake, it says that I must include recursive call to the function. Here it is:
I hope it is helpful for other learners too.

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

 採用された回答

Jan
Jan 2022 年 3 月 19 日

1 投票

If it is really the problem, that you use two functions, simply join then to one function:
function out = fibor(n, a, b)
if nargin == 1
out = fibor(n, 0, 1);
else % Here the "recursive tail":
if n == 0
out = a;
elseif n == 1
out = b;
else
out = [b, fibor(n-1, b, a+b)];
end
end
end

3 件のコメント

Duong Nguyen
Duong Nguyen 2022 年 3 月 19 日
It works very well, thank you.
Dhairya
Dhairya 2023 年 9 月 24 日
How did using 3 input arguments prevent the server from timing out? How does it prevent making large number of stacks?
Dyuman Joshi
Dyuman Joshi 2023 年 9 月 24 日
"How did using 3 input arguments prevent the server from timing out?"
What makes you think that using 3 (or more) input arguments will lead to the server being timed out?

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

その他の回答 (0 件)

カテゴリ

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

質問済み:

2022 年 3 月 19 日

コメント済み:

2023 年 9 月 24 日

Community Treasure Hunt

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

Start Hunting!

Translated by