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 nor can it compile a function M-file that calls a script.
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 matrix 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 [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
in the MATLAB workspace. If it is important to have m
accessible from the MATLAB workspace, you can change the beginning of the function to
![]() | Specifying S-Function Characteristics | Stand-Alone Applications | ![]() |