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

4 visualizzazioni (ultimi 30 giorni)
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 Commento
dpb
dpb il 14 Feb 2015
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...

Accedi per commentare.

Risposte (1)

David Young
David Young il 14 Feb 2015
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
>>

Categorie

Scopri di più su Scope Variables and Generate Names in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by