Programming and Data Types    

Local and Global Variables

The same guidelines that apply to MATLAB variables at the command line also apply to variables in M-files:

Ordinarily, each MATLAB function, defined by an M-file, has its own local variables, which are separate from those of other functions, and from those of the base workspace. However, 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 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.

For your MATLAB application to work with global variables:

MATLAB global variable names are typically longer and more descriptive than local variable names, and sometimes consist of all uppercase characters. These are not requirements, but guidelines to increase the readability of MATLAB code and reduce the chance of accidentally redefining a global variable.


 Passing Variable Numbers of Arguments Persistent Variables