
4 Programming
Like other functions, a neste d function has its own workspace where variables
used by the function are stored. B ut it also has a ccess to the w orkspaces
of all functions in which it is nested. So, for example, a variable that has
a value assigned to it by the primary function can be read or overwritten
by a function nested at any level w ithin the prim ary. Similarly, a variable
that is assigned in a nested function can be read or overwritten by any of the
functions containing that function.
Function Overloading
Overloaded functions act the same way as overloa d ed fun cti on s in most
computer languages. Overloaded functions are useful when you need to create
a function that responds to different types of inputs accordingly. For instance,
you might want one of your functions to accept both double-precision and
integer input, but to handle each type somewhat differently. You can make
thisdifferenceinvisibletotheuserbycreating two separate functions having
thesamename,anddesignatingonetohandle
double types and one to
handle integers. When you call the function, MATLAB chooses which M-file
to dispatch to based on the type of the input arguments.
Global Variables
If you want more than one function to share a single copy of a variable, simply
declare the variable as
global in all the functions. Do the same thing at
the command line if you want the base w orkspace to access the variable.
The global declaration must occur before the variable is actually used in a
function. Although it is not required, using capital letters for the names of
global variables helps distinguish them from other variables. For example,
create an M-file called
falling.m:
function h = f alling(t)
global GRAVITY
h = 1/2*GRAVITY*t.^2;
Then interactively enter the statements
global GRAVITY
GRAVITY = 32;
y = falling((0:.1:5)') ;
4-26
Commenti su questo manuale