Why does increasing the recursion limit to a number such as 5000 or more cause MATLAB to crash before the limit is reached?

I use the command
 
set(0,'RecursionLimit', 5000)
 
 to increase the recursion limit from 500 (default) to 5000, but when my recursive algorithm runs, it crashes MATLAB.

 Accepted Answer

The recursion limit is there specifically to avoid these types of crashes. Recursive functions have high memory requirements. Each recursion doubles the amount of memory that is allocated by the function and a stack is used to store the data. A stack consists of a limited amount of memory and when this limit is reached, the program cannot keep running.
 
This is not a limitation as it depends on how much memory each recursive function is using. In general, if you see a message about reaching the recursion limit, this should be a sign that there might be a syntax or design error in your program.
 
To solve this issue, divide the task in slices and apply the recursive algorithm to these slices.
 
To reproduce this issue, create the following file:
 
 
function retVal = myrecursivefun(inVal, recursions)
recursions = recursions - 1;
inVal = inVal + 1;
if recursions > 0
retVal = myrecursivefun(inVal, recursions);
else
retVal = inVal;
end
 
Then run it as follows to crash MATLAB:
 
set(0,'RecursionLimit', 5000);
myrecursivefun(1, 5000);
 

More Answers (0)

Categories

Find more on MATLAB Coder in Help Center and File Exchange

Products

Release

R2014a

Tags

No tags entered yet.

Community Treasure Hunt

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

Start Hunting!