MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

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.


Global Variables


Global variables are variables that you can access from functions or from the command
line. They have their own workspace, which is separate from the base and function
workspaces.


However, global variables carry notable risks. For example:



  • Any function can access and update a global variable. Other functions that use the
    variable might return unexpected results.

  • If you unintentionally give a “new” global variable the same name as an existing global
    variable, one function can overwrite the values expected by another. This error is
    difficult to diagnose.


Use global variables sparingly, if at all.


Share Data Between Workspaces
Free download pdf