MATLAB Compiler    

Simple Example

This example involves mixing M-files and C code. Consider a simple application whose source code consists of mrank.m and mrankp.c.

mrank.m

mrank.m contains a function that returns a vector of the ranks of the magic squares from 1 to n:

The Build Process

The steps needed to build this stand-alone application are

  1. Compile the M-code.
  2. Generate the library wrapper file.

To perform these steps, use

The MATLAB Compiler generates C source code files named mrank.c, Pkg.c, and Pkg.h. This command invokes mbuild to compile the resulting Compiler-generated source files (mrank.c, Pkg.c, Pkg.h) with the existing C source file (mrankp.c) and links against the required libraries. For details, see Building Stand-Alone C/C++ Applications.

The MATLAB Compiler provides two different versions of mrankp.c in the <matlab>/extern/examples/compiler directory:

Figure 4-3: Mixing M-Files and C Code to Form a Stand-Alone Application

mrankp.c

The code in mrankp.c calls mrank and outputs the values that mrank returns:

An Explanation of mrankp.c

The heart of mrankp.c is a call to the mlfMrank function. Most of what comes before this call is code that creates an input argument to mlfMrank. Most of what comes after this call is code that displays the vector that mlfMrank returns. First, the code must call the Compiler-generated library initialization function.

To understand how to call mlfMrank, examine its C function header, which is

According to the function header, mlfMrank expects one input parameter and returns one value. All input and output parameters are pointers to the mxArray data type. (See External Interfaces/API" in the MATLAB online documentation for details on the mxArray data type.) To create and manipulate mxArray * variables in your C code, you can call the mx routines described in the "External Interfaces/API" or any routine in the MATLAB C/C++ Math Library. For example, to create a 1-by-1 mxArray * variable named N with real data, mrankp calls mlfScalar:

mrankp can now call mlfMrank, passing the initialized N as the sole input argument.

mlfMrank returns a pointer to an mxArray * variable named R. The easiest way to display the contents of R is to call the mlfPrintMatrix convenience function:

mlfPrintMatrix is one of the many routines in the MATLAB Math Built-In Library, which is part of the MATLAB Math Library.

Finally, mrankp must free the heap memory allocated to hold matrices and call the Compiler-generated termination function:


  Mixing M-Files and C or C++ Advanced C Example