How to go to a main function from sub-function if sub-function is recursive? "return" does not work here

2 次查看(过去 30 天)
I have a recursive sub function i.e the sub function calls itself if a certain condition is not satisfied.I want to return from the sub function to the main function if another condition is satisfied.The "return" statement can go only to the invoking function. So if the sub function had invoked itself "return" does not help to go to the main function. Question is how can we get out of recursion and go to the main function. Thanks in advance.
  1 个评论
dpb
dpb 2015-2-14
As David shows, a completing recursive function has a normal exit. I presume your case is where there's a reason to abort early.
I think your only hope is to pass a flag that tells the higher-level call it also is to abort. This, passed up, will eventually get to the top.
Alternatively there could be an (ugh) global state.
Haven't thought this thru but wonder if you could encapsulate the call in try...catch block and then throw an error in the recursive function which the top level can process...

请先登录,再进行评论。

回答(1 个)

David Young
David Young 2015-2-14
If the recursive function is structured properly, returning from the final call when the termination condition is satisfied will return from each of the earlier calls, ending up at the calling function. Here's an example:
function recursiveFunction(N)
%RECURSIVEFUNCTION demonstrates a recursive function
% RECURSIVEFUNCTION(N) assumes that N is a positive scalar and prints N,
% N-1, N-2 ... T where 0 < T <= 1, followed by a message.
if N <= 0
disp('Finished recursion, returning to calling function');
return;
end
disp(N);
recursiveFunction(N-1);
end % of function
which when called does this:
>> recursiveFunction(3)
3
2
1
Finished recursion, returning to calling function
>>

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by