MATLAB: How to have a function check if it is being called recursively

MATLAB

I have a main function and several sub-functions that call each other, and the functions need to know if they are being called recursively or not. Is there a way to implement this in MATLAB?

Best Answer

You can use persistent or global variables in the functions to track how many times they have been called. Persistent variables are recommended over global variables because persistent variables only apply to the workspace of a single function and not all functions' workspaces. More information on persistent and global variables can be found at the following links:
The persistent variable approach works if the order of the stack does not matter. For each function, you can declare a count variable as persistent, increment it at the start of the function, and decrement it right before the end of the function. In this way, the count variable will keep track of how many instances of the function are on the stack at any time. The following is an example function that uses this approach:
 
function foo
persistent count;
if isempty(count)
    count = 1;
else
    count = count+1;
end
% Main body of function...
count = count - 1;
end
If you need to know the order of the functions on the stack then you could declare a global "stack" variable and update it in a similar way at the beginning and end of each function. Please make sure to clear the variable after everything finishes executing or else the variable will be available in all workspaces.