Programming and Data Types    

Global Variables

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.

Then interactively enter the statements

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:

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:

Suggestions for Using Global Variables

There is a certain amount of risk associated with using global variables and, because of this, it is recommended that you use them sparingly. You might, for example, unknowingly 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 unintentionally overwrite the variable used by the other. This can be a difficult error 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


  Local Variables Persistent Variables