MATLAB: Is the recursive function not exiting when I call return

functionMATLABrecursivereturn

I have a function with an if statement. The first part of the if statement is recursive, and then the else statement just says to "return". Why do I still appear to be in my function? Why is it not exiting from the "return" function?

Best Answer

Recursive functions can be tricky. Remember, calling "return" only returns for the most recent function.
See attached image.
Calling return when inside the fourth call of the recursive function, only exits that fourth call. The other three calls of the function are still running.
In some cases, it is better to use an iterative approach such as a for loop or while loop instead of a recursive approach.