Code Generation for Recursive Functions
To generate code for recursive MATLAB® functions, the code generator uses compile-time recursion or run-time recursion. You can influence whether the code generator uses compile-time or run-time recursion by modifying your MATLAB code. See Force Code Generator to Use Run-Time Recursion.
When you use recursive functions in MATLAB code that is intended for code generation, you must adhere to certain restrictions. See Recursive Function Limitations for Code Generation.
With compile-time recursion, the code generator creates multiple versions of a recursive function in the generated code. The inputs to each version have values or sizes that are customized for that version. These versions are known as function specializations. You can tell that the code generator used compile-time recursion by looking at the MATLAB Function report or the generated C code. Here is an example of compile-time recursion in the report.
With run-time recursion, the code generator produces a recursive function in the generated code. You can tell that the code generator used run-time recursion by looking at the MATLAB Function report or the generated C code. Here is an example of run-time recursion in the report.
In the model configuration parameters, set Compile-time recursion limit for MATLAB functions to 0.
Disable Run-Time Recursion
Some coding standards, such as MISRA™, do not allow recursion. To increase the likelihood of generating code that is compliant with MISRA C™, disable run-time recursion.
In the model configuration parameters, clear the Enable run-time recursion for MATLAB functions check box.
If your code requires run-time recursion and run-time recursion is disabled, you must rewrite your code so that it uses compile-time recursion or does not use recursion.
Recursive Function Limitations for Code Generation
When you use recursion in MATLAB code that is intended for code generation, follow these restrictions:
The top-level function in a MATLAB Function block cannot be a recursive function, but it can call a recursive function.
Assign all outputs of a run-time recursive function before the first recursive call in the function.
Assign all elements of cell array outputs of a run-time recursive function.
Inputs and outputs of run-time recursive functions cannot be classes.
The Maximum stack size parameter is ignored for run-time recursion.