Define persistent variable

`persistent var1 ... varN`

`persistent var1 ... varN`

declares variables `var1 ... varN`

as persistent. Persistent variables are local to the function in which they are declared, yet their values are retained in memory between calls to the function. Code at the MATLAB^{®} command line and in other functions cannot change persistent variables.

When MATLAB first encounters a particular `persistent`

statement, it initializes the persistent variable to an empty matrix (`[]`

).

MATLAB clears persistent variables when you clear or modify a function that
is in memory. To keep a function in memory, use `mlock`

.

Persistent variables are similar to global variables because MATLAB creates permanent storage for both. They differ from global variables because persistent variables are known only to the function that declares them. Therefore, code at the MATLAB command line or other functions cannot change persistent variables.

Since MATLAB initializes a persistent variable to an empty matrix (

`[]`

), typically functions check to see if a persistent variable is empty, and, if so, initialize it.function myFun() persistent n if isempty(n) n = 0; end n = n+1; end

The declaration of a variable as persistent must precede any other references to the variable, including input or output arguments. For example, the

`persistent`

declarations in the following functions are invalid.function myfunA(x) persistent x end function myfunB x = 0; persistent x end

To clear a persistent variable, use

`clear`

with the name of the function that declares the variable. For example,`clear myFun`

.