User`s guide

Coding with M-Files Only
4-31
Coding with M-Files Only
One way to create a stand-alone application is to write all the source code in
one or more M-files or MEX-files. Coding an application in M-files allows you
to take advantage of MATLAB’s interpretive development environment. Then,
after getting the M-file version of your program working properly, compile the
code and build it into a stand-a lone application.
Note It is goo d practice to avoi d manually modif y ing the C or C++ c o d e t hat
the MATLAB Comp i ler gen erates. If t he generated C or C+ + code is not to
your l iking, modify the M-file (and/or the compiler options) and then
recompile. If you do edit the generated C or C++ code, remember that your
changes will be erased the next time you recompile the M-file. For more
information, se e “Compiling MATLAB Prov ided M - Files Separa te ly ” on page
4-35 and “Int erf acing M-Cod e to C/C++ C o de” in Chapter 5 .
Consider a very simple application whose source code consists of two M-files,
mrank.m and main.m. This example involves C code; y ou use a similar process
(described below) for C++ code. In this example, the line
r = zeros(n,1)
preallocates memory to help the performance of the Co mpile r.
mrank.m returns a vector of integers, r. Each element of r represents the rank
ofamagic square.Forexample,aftert he function completes,
r(3) contains the
rank of a 3-by-3 magic square.
function r = mrank(n)
r = zeros(n,1);
for k = 1:n
r(k) = rank(magic(k));
end
main.m
contains a “main routine” that calls mrank and then prints the results
function main
r = mrank(5)
To compile these into code that can be built into a stand-alone application,
invoke the MATLAB Compiler.
mcc -mc main mrank