Compile-Time Recursion Limit Reached

Issue

You see this error message:

Compile-time recursion limit reached. Increase CompileTimeRecursionLimit.

Cause

With compile-time recursion, the code generator produces copies of the recursive function instead of producing a recursive function in the generated code. The code generator is unable to use compile-time recursion for a recursive function in your MATLAB® code because the number of function copies exceeds the limit.

Solution

To address this issue, try one of these solutions:

Use Run-Time Recursion by Making the Recursive Function Input Variable-Size

Consider this function:

function z = call_mysum(A)
%#codegen
z = mysum(A);
end

function y = mysum(A)
coder.inline('never');
if size(A,2) == 1
    y = A(1);
else
    y = A(1)+ mysum(A(2:end));
end
end

If the input to mysum is fixed-size, the code generator uses compile-time recursion. If A is large enough, the number of function copies exceeds the default limit of 50. To cause the code generator to use run-time conversion, make the input to mysum variable-size by using coder.varsize.

function z = call_mysum(A)
%#codegen
B = A;
coder.varsize('B');
z = mysum(B);
end

function y = mysum(A)
coder.inline('never');
if size(A,2) == 1
    y = A(1);
else
    y = A(1)+ mysum(A(2:end));
end
end

Increase the Compile-Time Recursion Limit

The default compile-time recursion limit of 50 is high enough for most recursive functions that require compile-time recursion. Usually, increasing the limit does not fix the issue. However, if you can determine the number of recursive calls and you want compile-time recursion, increase the limit. For example, consider this function:

function z = call_mysum()
%#codegen
B = 1:125;
z = mysum(B);
end

function y = mysum(A)
coder.inline('never');
if size(A,2) == 1
    y = A(1);
else
    y = A(1)+ mysum(A(2:end));
end
end

You can determine that the code generator produces 125 copies of the mysum function. In this case, if you want compile-time recursion, increase the compile-time recursion limit to 125.

To increase the compile-time recursion limit:

  • At the command line, in a code generation configuration object, increase the value of the CompileTimeRecursionLimit configuration parameter.

  • In the MATLAB Coder™ app, increase the value of the Compile-time recursion limit setting.

More About

Was this topic helpful?