Variables

Chapter 2 introduced variable naming and data types. Here, we continue to introduce knowledge related to variables, including variable scope and lifetime, discussing variable validity from the dimensions of space and time.

Variable Scope

Some variables can function throughout the entire program, while others can only function within a certain range of the program. The scope of a variable is called its scope. Based on scope, variables can be divided into the following two types:

Local Variables

Each MATLAB function has its own local variables. The scope of local variables is limited to the function itself. Once the program execution goes beyond this function, the variable values will no longer be retained.

Global Variables

Global variables are declared using the global keyword, and their scope covers the entire M-file.

If you want to extend the scope of a variable, you can use two methods. One method is to pass the variable as a function parameter; the other method is to declare the variable as a global variable.

Note: Passing variables as function parameters is safer because when declaring them as global variables, you might unintentionally change the variable's value. In such cases, the program might still run, but the results may be incorrect, and errors are harder to troubleshoot.

Variable Lifetime

The lifetime of a variable represents its ability to retain its value. In MATLAB, there is a type of variable called a persistent variable. Persistent variables are similar to static variables in languages like C and Basic, meaning they can retain variable values. Persistent variables are declared using the persistent keyword and have the following characteristics:

Can only be used inside functions;

Other functions cannot access them;

MATLAB does not clear them from memory while the function exists, so the variable can always retain its value;

If the function is cleared or its M-file is edited, MATLAB will clear all persistent variables used by that function.

You can use the mlock function to prevent an M-file from being cleared from memory, thus preventing persistent variables within the M-file from being cleared as well.