function nestedFx
x = x + 1;
end
end
When parent functions do not use a given variable, the variable remains local to the nested function.
For example, in this version of primaryFx, the two nested functions have their own versions of x that
cannot interact with each other.
function primaryFx
nestedFx1
nestedFx2
function nestedFx1
x = 1;
end
function nestedFx2
x = 2;
end
end
For more information, see “Nested Functions” on page 20-27.
Persistent Variables
When you declare a variable within a function as persistent, the variable retains its value from one
function call to the next. Other local variables retain their value only during the current execution of
a function. Persistent variables are equivalent to static variables in other programming languages.
Declare variables using the persistent keyword before you use them. MATLAB initializes persistent
variables to an empty matrix, [].
For example, define a function in a file named findSum.m that initializes a sum to 0, and then adds to
the value on each iteration.
function findSum(inputvalue)
persistent SUM_X
if isempty(SUM_X)
SUM_X = 0;
end
SUM_X = SUM_X + inputvalue;
When you call the function, the value of SUM_X persists between subsequent executions.
These operations clear the persistent variables for a function:
• clear all
• clear functionname
• Editing the function file
To prevent clearing persistent variables, lock the function file using mlock.
Share Data Between Workspaces
20-11
x = x + 1;
end
end
When parent functions do not use a given variable, the variable remains local to the nested function.
For example, in this version of primaryFx, the two nested functions have their own versions of x that
cannot interact with each other.
function primaryFx
nestedFx1
nestedFx2
function nestedFx1
x = 1;
end
function nestedFx2
x = 2;
end
end
For more information, see “Nested Functions” on page 20-27.
Persistent Variables
When you declare a variable within a function as persistent, the variable retains its value from one
function call to the next. Other local variables retain their value only during the current execution of
a function. Persistent variables are equivalent to static variables in other programming languages.
Declare variables using the persistent keyword before you use them. MATLAB initializes persistent
variables to an empty matrix, [].
For example, define a function in a file named findSum.m that initializes a sum to 0, and then adds to
the value on each iteration.
function findSum(inputvalue)
persistent SUM_X
if isempty(SUM_X)
SUM_X = 0;
end
SUM_X = SUM_X + inputvalue;
When you call the function, the value of SUM_X persists between subsequent executions.
These operations clear the persistent variables for a function:
• clear all
• clear functionname
• Editing the function file
To prevent clearing persistent variables, lock the function file using mlock.
Share Data Between Workspaces
20-11
