Define and Initialize Persistent Variables

Persistent variables are local to the function in which they are defined, but they retain their values in memory between calls to the function. To define persistent variables for C/C++ code generation, use the persistent statement, as in this example:

persistent PROD_X;

The definition should appear at the top of the function body, after the header and comments, but before the first use of the variable. During code generation, the value of the persistent variable is initialized to an empty matrix by default. You can assign your own value after the definition by using the isempty statement, as in this example:

function findProduct(inputvalue) %#codegen
persistent PROD_X

if isempty(PROD_X)
   PROD_X = 1;
PROD_X = PROD_X * inputvalue;
Was this topic helpful?