User`s guide

Converting Script M-Files to Function M-Files
3-11
Converting Script M-Files to Function M-Files
MATLAB provides two ways to package sequences of MATLAB commands:
Function M-files
S cript M - files
These two categories of M -files differ in two important respects:
You can pass arguments to function M-files but not to script M-files.
Variables used inside function M-files are local to that function; you cannot
access these variables from the MATLAB interpreter’s workspace unless
they are passed back by the function. By contrast, variables used inside
script M-files are shared with the caller’s workspace; you can access these
variables from the MATLAB interpreter command line.
The MATLAB Compiler cannot compile script M-files nor can it compile a
function M-file that calls a script.
Converting a script into a funct ion is usually fairly simple. To convert a script
to a function, simply add a
function line at the top of the M- file.
Forexample,considerthescriptM-file
houdini.m.
m = magic(4); % Assign 4x4 matrix to m.
t = m .^ 3; % Cube each element of m.
disp(t); % Display the value of t.
Running this script M-filefroma MATLAB session creates variables m and t in
your MATLAB workspace.
The MATLAB Compiler cannot compile
houdini.m because houdini.m is a
script. Convert this script M-file into a function M-file by simply adding a
function header line.
function [m,t] = houdini(sz)
m = magic(sz); % Assign matrix to m.
t = m .^ 3; % Cube each element of m.
disp(t) % Display the value of t.
The MATLAB Compiler can now compile houdini.m. However, because this
makes
houdini a function, running houdini.mex no longer creates variable m