Can someone explain how this recursive function works step by step?

4 ビュー (過去 30 日間)
AStar
AStar 2019 年 12 月 1 日
コメント済み: AStar 2019 年 12 月 1 日
function outvar = recurfn(num) % Format: recurfn(number)
if num < 0
outvar = 2;
else
outvar = 4 + recurfn(num-1);
end
end
Can someone explain to me how this recursive function works step by step?
for example without using MATLAB how would i figure out the result of recurfn(1) or recurfn(2)?
Thanks!

採用された回答

Stephane
Stephane 2019 年 12 月 1 日
編集済み: Stephane 2019 年 12 月 1 日
You simply add the sequence over and over (decreasing num by 1 each time), up until you reach the stop signal (num < 0).
This gives
recurfn(2) = 4 + recurfn(1)
= 4 + [ 4 + recurfn(0) ]
= 4 + 4 + [ 4 + recurfn(-1) ]
= 4 + 4 + 4 + 2

その他の回答 (1 件)

Jesus Sanchez
Jesus Sanchez 2019 年 12 月 1 日
function outvar = recurfn(num) % Format: recurfn(number)
if num < 0
outvar = 2;
else
outvar = 4 + recurfn(num-1);
end
end
As fas as I understand this, the function will call itself forever until num has a value less than 0. Thus, outvar is fixed to 2.
  2 件のコメント
AStar
AStar 2019 年 12 月 1 日
Thanks for your answer, but I dont think you understand my question. I am asking for an explanation of the logic required to answer this question without using the MATLAB software. How can one determine for example recurfn(2), recurfn(4) etc without actually calling those in the command window.
Jesus Sanchez
Jesus Sanchez 2019 年 12 月 1 日
See answer of Stephane. I am wrong

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

カテゴリ

Help Center および File ExchangeEnvironment and Settings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by