Main Content

Code Generation for Nested Functions

You can generate code for MATLAB® functions that contain nested functions. For example, you can generate code for the function parent_fun, which contains the nested function child_fun.

function parent_fun
x = 5;

    function child_fun
        x = x + 1;


Nested Function Limitations for Code Generation

When you generate code for nested functions, you must adhere to the code generation restrictions for value classes, cell arrays, and handle classes. You must also adhere to these restrictions:

  • If the parent function declares a persistent variable, it must assign the persistent variable before it calls a nested function that uses the persistent variable.

  • A nested recursive function cannot refer to a variable that the parent function uses.

  • If a nested function refers to a structure variable, you must define the structure by using struct.

  • If a nested function uses a variable defined by the parent function, you cannot use coder.varsize with the variable in either the parent or the nested function.

Related Topics