MATLAB Function Reference Previous page   Next Page
persistent

Define persistent variable

Syntax

Description

persistent X Y Z defines X, Y, and Z as variables that are local to the function in which they are declared; yet their values are retained in memory between calls to the function. Persistent variables are similar to global variables because MATLAB creates permanent storage for both. They differ from global variables in that persistent variables are known only to the function in which they are declared. This prevents persistent variables from being changed by other functions or from the MATLAB command line.

Persistent variables are cleared when the M-file is cleared from memory or when the M-file is changed. To keep an M-file in memory until MATLAB quits, use mlock.

If the persistent variable does not exist the first time you issue the persistent statement, it is initialized to the empty matrix.

It is an error to declare a variable persistent if a variable with the same name exists in the current workspace.

Remarks

There is no function form of the persistent command (i.e., you cannot use parentheses and quote the variable names).

Example

This function prompts a user to enter a directory name to use in locating one or more files. If the user has already entered this information, and it requires no modification, they do not need to enter it again. This is because the function stores it in a persistent variable (lastDir), and offers it as the default selection. Here is the function definition:

Execute the function twice. The first time, it prompts you to enter the information and does not offer a default:

The second time, it does offer a default taken from the persistent variable dirName:

See Also

global, clear, mislocked, mlock, munlock, isempty


Previous page  permute pi Next page

© 1994-2005 The MathWorks, Inc.