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:
A
and a
are not the same variable.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.
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.
For your MATLAB application to work with global variables:
global
in every function that requires access to it. To enable the workspace to access the global variable, also declare it as global
from the command line.global
command before the first occurrence of the variable name. The top of the M-file is recommended.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 | ![]() |