Next: For-loops
Up: MATLAB summary
Previous: Plotting
The code for a MATLAB function must be put in a file. The name of
the function, so far as MATLAB is concerned, is the name of the file.
The function also has a name, which essentially plays no role at
the moment, but it is good practice to make this the same as the file name.
Therefore if we have the following code (which smooths periodic functions, i.e.
those that `wrap around' at the ends) in a file called
smoothit.m
function [xout] = smoothit(xin);
nx = length(xin);
xleft = [xin(nx) xin(1:nx-1)];
xright = [xin(2:nx) xin(1)];
weight1 = 4;
weight2 = 2;
xout = xleft/weight1 + xin/weight2 + xright/weight1;
we find the following
>> x=[1 3 5 3 1]
x =
1 3 5 3 1
>> y=smoothit(x)
y =
1.5000 3.0000 4.0000 3.0000 1.5000
>>
The only communication with the function smoothit.m and
the base workspace is via the input argument xin,
and the output argument xout. Therefore,
the values of weight1 and weight2, for example, are
undefined except while smoothit.m
is executing, i.e.
>> y=smoothit(x);
>> weight1
??? Undefined function or variable 'weight1'.
If we want the value of weight1 to be saved, or alternatively if we
want to pass a value to the function from the base workspace
other than by the function arguments, we
can use the global command. To do this we modify smoothit.m:
function [xout] = smoothit(xin);
global weight1 weight2 % add this before any executable statement
and similarly at the MATLAB prompt (or more typically in a MATLAB
script) type
>> global weight1 weight2
>> y=smoothit(x);
Then after executing smoothit.m we find
that both weight1 and weight2 are defined in the base workspace.
In summary, the global statement allows variables to be
shared between MATLAB functions and the base workspace, i.e. to have a global
role.
Charlie Macaskill
Fri Mar 5 16:05:28 EST 1999