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

조회 수: 4 (최근 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에서 Scope Variables and Generate Names에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by