| MATLAB Compiler | ![]() |
Converting Script M-Files to Function M-Files
MATLAB provides two ways to package sequences of MATLAB commands:
These two categories of M-files differ in two important respects:
The MATLAB Compiler cannot compile script M-files, however, it can compile function M-files that call scripts. You may not specify a script M-file explicitly on the mcc command line, but you may specify function M-files that include scripts themselves.
Converting a script into a function is usually fairly simple. To convert a script to a function, simply add a function line at the top of the M-file.
For example, consider the script M-file houdini.m.
m = magic(4); % Assign 4x4 magic square to m. t = m .^ 3; % Cube each element of m. disp(t); % Display the value of t.
Running this script M-file from a 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 houdini(sz) m = magic(sz); % Assign magic square 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.m no longer creates variables m and t in the MATLAB workspace. If it is important to have m and t accessible from the MATLAB workspace, you can change the beginning of the function to
The function now returns the values of m and t to its caller.
| Using Pragmas | Including Script Files in Deployed Applications | ![]() |
© 1994-2005 The MathWorks, Inc.