MATLAB Compiler Previous page   Next Page

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.
  3. Create the binary executable.

To perform these steps, use

The MATLAB Compiler generates the following C source code files:

This command invokes mbuild to compile the resulting Compiler-generated source files with the existing C source file (mrankp.c) and link against the required libraries.

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

flowchart showing the mixing of m files and c code to form a stand alone application

Figure 6-1: 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 initialize the MCR and the generated libPkg library.

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 the External Interfaces 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 documentation. For example, to create a 1-by-1 mxArray * variable named N with real data, mrankp calls mxCreateScalarDouble.

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

mlfMrank returns its output in a newly allocated mxArray * variable named R. The variable R is initialized to NULL. Output variables that have not been assigned to a valid mxArray should be set to NULL. The easiest way to display the contents of R is to call the mlfPrintmatrix function.

This function is defined in Printmatrix.m.

Finally, mrankp must free the heap memory allocated to hold matrices and call the termination functions.


Previous page  Mixing M-Files and C or C++ Advanced C Example Next page

© 1994-2005 The MathWorks, Inc.