| MATLAB® | ![]() |
| On this page… |
|---|
A MATLAB® variable is essentially a tag that you assign to a value while that value remains in memory. The tag gives you a way to reference the value in memory so that your programs can read it, operate on it with other data, and save it back to memory.
MATLAB provides three basic types of variables:
Each MATLAB function has its own local variables. These are separate from those of other functions (except for nested functions), and from those of the base workspace. Variables defined in a function do not remain in memory from one function call to the next, unless they are defined as global or persistent.
Scripts, on the other hand, do not have a separate workspace. They store their variables in a workspace that is shared with the caller of the script. When called from the command line, they share the base workspace. When called from a function, they share that function's workspace.
Note If you run a script that alters a variable that already exists in the caller's workspace, that variable is overwritten by the script. |
If several functions, and possibly the base workspace, all declare a particular name as global, then they all share a single copy of that variable. Any assignment to that variable, in any function, is available to all the other functions declaring it global.
Suppose, for example, you want to study the effect of the interaction coefficients, α and β, in the Lotka-Volterra predator-prey model.
![]()
Create an M-file, lotka.m.
function yp = lotka(t,y) %LOTKA Lotka-Volterra predator-prey model. global ALPHA BETA yp = [y(1) - ALPHA*y(1)*y(2); -y(2) + BETA*y(1)*y(2)];
Then interactively enter the statements
global ALPHA BETA ALPHA = 0.01 BETA = 0.02 [t,y] = ode23(@lotka,[0,10],[1; 1]); plot(t,y)
The two global statements make the values assigned to ALPHA and BETA at the command prompt available inside the function defined by lotka.m. They can be modified interactively and new solutions obtained without editing any files.
Creating Global Variables. Each function that uses a global variable must first declare the variable as global. It is usually best to put global declarations toward the beginning of the function. You would declare global variable MAXLEN as follows:
global MAXLEN
If the M-file contains subfunctions as well, then each subfunction requiring access to the global variable must declare it as global. To access the variable from the MATLAB command line, you must declare it as global at the command line.
MATLAB global variable names are typically longer and more descriptive than local variable names, and often consist of all uppercase characters. These are not requirements, but guidelines to increase the readability of MATLAB code, and to reduce the chance of accidentally redefining a global variable.
Displaying Global Variables. To see only those variables you have declared as global, use the who or whos functions with the literal, global.
global MAXLEN MAXWID MAXLEN = 36; MAXWID = 78; len = 5; wid = 21; whos global Name Size Bytes Class MAXLEN 1x1 8 double array (global) MAXWID 1x1 8 double array (global) Grand total is 2 elements using 16 bytes
Suggestions for Using Global Variables. A certain amount of risk is associated with using global variables and, because of this, it is recommended that you use them sparingly. You might, for example, unintentionally give a global variable in one function a name that is already used for a global variable in another function. When you run your application, one function may overwrite the variable used by the other. This error can be difficult to track down.
Another problem comes when you want to change the variable name. To make a change without introducing an error into the application, you must find every occurrence of that name in your code (and other people's code, if you share functions).
Alternatives to Using Global Variables. Instead of using a global variable, you may be able to
Pass the variable to other functions as an additional argument. In this way, you make sure that any shared access to the variable is intentional.
If this means that you have to pass a number of additional variables, you can put them into a structure or cell array and just pass it as one additional argument.
Use a persistent variable (described in the next section), if you only need to make the variable persist in memory from one function call to the next.
Characteristics of persistent variables are
You can declare and use them within M-file functions only.
Only the function in which the variables are declared is allowed access to it.
MATLAB does not clear them from memory when the function exits, so their value is retained from one function call to the next.
You must declare persistent variables before you can use them in a function. It is usually best to put your persistent declarations toward the beginning of the function. You would declare persistent variable SUM_X as follows:
persistent SUM_X
If you clear a function that defines a persistent variable (i.e., using clear functionname or clear all), or if you edit the M-file for that function, MATLAB clears all persistent variables used in that function.
You can use the mlock function to keep an M-file from being cleared from memory, thus keeping persistent variables in the M-file from being cleared as well.
Initializing Persistent Variables. When you declare a persistent variable, MATLAB initializes its value to an empty matrix, []. After the declaration statement, you can assign your own value to it. This is often done using an isempty statement, as shown here:
function findSum(inputvalue) persistent SUM_X if isempty(SUM_X) SUM_X = 0; end SUM_X = SUM_X + inputvalue
This initializes the variable to 0 the first time you execute the function, and then it accumulates the value on each iteration.
MATLAB variable names must begin with a letter, which may be followed by any combination of letters, digits, and underscores. MATLAB distinguishes between uppercase and lowercase characters, so A and a are not the same variable.
Although variable names can be of any length, MATLAB uses only the first N characters of the name, (where N is the number returned by the function namelengthmax), and ignores the rest. Hence, it is important to make each variable name unique in the first N characters to enable MATLAB to distinguish variables.
N = namelengthmax
N =
63The genvarname function can be useful in creating variable names that are both valid and unique. See the genvarname reference page to find out how to do this.
You can use the isvarname function to make sure a name is valid before you use it. isvarname returns 1 if the name is valid, and 0 otherwise.
isvarname 8th_column
ans =
0 % Not valid - begins with a numberWhen naming a variable, make sure you are not using a name that is already used as a function name, either one of your own M-file functions or one of the functions in the MATLAB language. If you define a variable with a function name, you will not be able to call that function until you either remove the variable from memory with the clear function, or invoke the function using builtin.
For example, if you enter the following command, you will not be able to use the MATLAB disp function until you clear the variable with clear disp.
disp = 50;
To test whether a proposed variable name is already used as a function name, use
which -all variable_name
There are some MATLAB functions that have names that are commonly used as variable names in programming code. A few examples of such functions are i, j, mode, char, size, and path.
If you need to use a variable that is also the name of a MATLAB function, and have determined that you have no need to call the function, you should be aware that there is still a possibility for conflict. See the following two examples:
Variables Loaded From a MAT-File. The function shown below loads previously saved data from MAT-file settings.mat. It is supposed to display the value of one of the loaded variables, mode. However, mode is also the name of a MATLAB function and, in this case, MATLAB interprets it as the function and not the variable loaded from the MAT-file:
function show_mode
load settings;
whos mode
fprintf('Mode is set to %s\n', mode)
Assume that mode already exists in the MAT-file. Execution of the function shows that, even though mode is successfully loaded into the function workspace as a variable, when MATLAB attempts to operate on it in the last line, it interprets mode as a function. This results in an error:
show_mode
Name Size Bytes Class
mode 1x6 12 char array
Grand total is 6 elements using 12 bytes
??? Error using ==> mode
Not enough input arguments.
Error in ==> show_mode at 4
fprintf('Mode is set to %s\n', mode)
Because MATLAB parses function M-files before they are run, it needs to determine before runtime which identifiers in the code are variables and which are functions. The function in this example does not establish mode as a variable name and, as a result, MATLAB interprets it as a function name instead.
There are several ways to make this function work as intended without having to change the variable name. Both indicate to MATLAB that the name represents a variable, and not a function:
Name the variable explicitly in the load statement:
function show_mode
load settings mode;
whos mode
fprintf('Mode is set to %s\n', mode)
Initialize the variable (e.g., set it to an empty matrix or empty string) at the start of the function:
function show_mode
mode = '';
load settings;
whos mode
fprintf('Mode is set to %s\n', mode)
Variables In Evaluation Statements. Variables used in evaluation statements such as eval, evalc, and evalin can also be mistaken for function names. The following M-file defines a variable named length that conflicts with MATLAB length function:
function find_area
eval('length = 12; width = 36;');
fprintf('The area is %d\n', length .* width)
The second line of this code would seem to establish length as a variable name that would be valid when used in the statement on the third line. However, when MATLAB parses this line, it does not consider the contents of the string that is to be evaluated. As a result, MATLAB has no way of knowing that length was meant to be used as a variable name in this program, and the name defaults to a function name instead, yielding the following error:
find_area ??? Error using ==> length Not enough input arguments.
To force MATLAB to interpret length as a variable name, use it in an explicit assignment statement first:
function find_area
length = [];
eval('length = 12; width = 36;');
fprintf('The area is %d\n', length .* width)The same guidelines that apply to MATLAB variables at the command line also apply to variables in M-files:
You do not need to type or declare variables used in M-files (with the possible exception of designating them as global or persistent).
Before assigning one variable to another, you must be sure that the variable on the right-hand side of the assignment has a value.
Any operation that assigns a value to a variable creates the variable, if needed, or overwrites its current value, if it already exists.
MATLAB stores variables in a part of memory called a workspace. The base workspace holds variables created during your interactive MATLAB session and also any variables created by running M-file scripts. Variables created at the MATLAB command prompt can also be used by scripts without having to declare them as global.
Functions do not use the base workspace. Every function has its own function workspace. Each function workspace is kept separate from the base workspace and all other workspaces to protect the integrity of the data used by that function. Even subfunctions that are defined in the same M-file have a separate function workspace.
In most cases, variables created within a function are known only within that function. These variables are not available at the MATLAB command prompt or to any other function or subfunction.
Passing Variables from Another Workspace. The most secure way to extend the scope of a function variable is to pass it to other functions as an argument in the function call. Since MATLAB passes data only by value, you also need to add the variable to the return values of any function that modifies its value.
Evaluating in Another Workspace Using evalin. Functions can also obtain variables from either the base or the caller's workspace using the evalin function. The example below, compareAB_1, evaluates a command in the context of the MATLAB command line, taking the values of variables A and B from the base workspace.
Define A and B in the base workspace:
A = [13 25 82 68 9 15 77]; B = [63 21 71 42 30 15 22];
Use evalin to evaluate the command A(find(A<=B)) in the context of the MATLAB base workspace:
function C = compareAB_1
C = evalin('base', 'A(find(A<=B))');Call the function. You do not have to pass the variables because they are made available to the function via the evalin function:
C = compareAB_1
C =
13 9 15You can also evaluate in the context of the caller's workspace by specifying 'caller' (instead of 'base') as the first input argument to evalin.
Using Global Variables. A third way to extend variable scope is to declare the variable as global within every function that needs access to it. If you do this, you need make sure that no functions with access to the variable overwrite its value unintentionally. For this reason, it is recommended that you limit the use of global variables.
Create global vectors A and B in the base workspace:
global A global B A = [13 25 82 68 9 15 77]; B = [63 21 71 42 30 15 22];
Also declare them in the function to be called:
function C = compareAB_2 global A global B C = A(find(A<=B));
Call the function. Again, you do not have to pass A and B as arguments to the called function:
C = compareAB_2
C =
13 9 15Variables within nested functions are accessible to more than just their immediate function. As a general rule, the scope of a local variable is the largest containing function body in which the variable appears, and all functions nested within that function. For more information on nested functions, see Variable Scope in Nested Functions.
Variables created at the MATLAB command prompt or in an M-file script exist until you clear them or end your MATLAB session. Variables in functions exist only until the function completes unless they have been declared as global or persistent.
![]() | MATLAB® Commands | Keywords | ![]() |
| © 1984-2008- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |