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

2 views (last 30 days)
AStar on 1 Dec 2019
Commented: AStar on 1 Dec 2019
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 on 1 Dec 2019
Edited: Stephane on 1 Dec 2019
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 CommentShowHide None
AStar on 1 Dec 2019
Thanks!

### More Answers (1)

Jesus Sanchez on 1 Dec 2019
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 CommentsShowHide 1 older comment
Jesus Sanchez on 1 Dec 2019
See answer of Stephane. I am wrong