| Products & Services | Industries | Academia | Support | User Community | Company |
| Download Product Updates | | | Get Pricing | | | Trial Software |
| Documentation → MATLAB |
| Contents | Index |
| Learn more about MATLAB |
| On this page… |
|---|
You create binary MEX-files using the mex build script. mex compiles and links source files into a shared library called a binary MEX-file, which you can run at the MATLAB command line. Once compiled, you treat binary MEX-files exactly like MATLAB M-files and built-in functions.
This section explains the components of a source MEX-file, statements you use in a program source file. Unless otherwise specified, the term "MEX-file" refers to a source file.
The MEX-file consists of:
A Gateway Routine that interfaces C and MATLAB data.
A Computational Routine written in C that performs the computations you want implemented in the binary MEX-file.
Preprocessor Macros for building platform-independent code.
The gateway routine is the entry point to the MEX-file shared library. It is through this routine that MATLAB accesses the rest of the routines in your MEX-files. Use the following guideline to create a gateway routine:
The following is a sample C MEX-file gateway routine:
void mexFunction(
int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
/* more C code ... */
}The name of the gateway routine must be mexFunction.
A gateway routine must contain the parameters prhs, nrhs, plhs, and nlhs described in the following table.
| Parameter | Description |
|---|---|
| prhs | An array of right-hand input arguments. |
| plhs | An array of left-hand output arguments. |
| nrhs | The number of right-hand arguments, or the size of the prhs array. |
| nlhs | The number of left-hand arguments, or the size of the plhs array. |
Declare prhs and plhs as type mxArray *, which means they point to MATLAB arrays. They are vectors that contain pointers to the arguments of the MEX-file.
You can think of the name prhs as representing the "parameters, right-hand side," that is, the input parameters. Likewise, plhs represents the "parameters, left-hand side," or output parameters.
It is good practice to write the gateway routine to call a Computational Routine; however, this is not required. The computational code can be part of the gateway routine. If you use both gateway and computational routines, you can combine them into one source file or into separate files. If you use separate files, the gateway routine must be the first source file listed in the mex command.
The name of the file containing your gateway routine is important, as explained in Naming the MEX-File.
The MATLAB C and Fortran API Reference describes functions you can use in your gateway and computational routines that interact with MATLAB programs and the data in the MATLAB workspace. The mx prefixed functions provide access methods for manipulating MATLAB arrays. The mex prefixed functions perform operations in the MATLAB environment.
To use the functions in the C and Fortran Reference library you must include the mex header, which declares the entry point and interface routines. Put this statement in your source file:
#include "mex.h"
The binary MEX-file name, and hence the name of the function you use in MATLAB, is the name of the source file containing your gateway routine.
The file extension of the binary MEX-file is platform-dependent. You find the file extension using the mexext function, which returns the value for the current machine.
The computational routine contains the code for performing the computations you want implemented in the binary MEX-file. Computations can be numerical computations as well as inputting and outputting data. The gateway calls the computational routine as a subroutine.
The programming requirements described in Creating and Using Source Files, Using MATLAB Libraries, and Required Header Files might also apply to your computational routine.
The mx and mex functions use the MATLAB preprocessor macros mwSize and mwIndex for cross-platform flexibility. mwSize represents size values, such as array dimensions and number of elements. mwIndex represents index values, such as indices into arrays.
The following examples illustrate data flow in MEX-files:
Suppose your MEX-file myFunction has two input arguments and one output argument. The MATLAB syntax is [X] = myFunction(Y, Z). To call myFunction from MATLAB, type:
X = myFunction(Y, Z);
The MATLAB interpreter calls mexFunction, the gateway routine to myFunction, with the following arguments:

Your input is prhs, a 2-element C array (nrhs = 2). The first element is a pointer to an mxArray named Y and the second element is a pointer to an mxArray named Z.
Your output is plhs, a 1-element C array (nlhs = 1) where the single element is a null pointer. The parameter plhs points at nothing because the output X is not created until the subroutine executes.
The gateway routine creates the output array and sets a pointer to it in plhs[0]. If the routine does not assign a value to plhs[0] but you assign an output value to the function when you call it, MATLAB generates an error.
Note It is possible to return an output value even if nlhs = 0. This corresponds to returning the result in the ans variable. |
The following MEX Cycle diagram shows how inputs enter a MEX-file, what functions the gateway routine performs, and how outputs return to MATLAB.
In this example, the syntax of the MEX-file func is [C, D] = func(A,B). In the figure, a call to func tells MATLAB to pass variables A and B to your MEX-file. C and D are left unassigned.
The gateway routine func.c uses the mxCreate* functions to create the MATLAB arrays for your output arguments. It sets plhs[0] and plhs[1] to the pointers to the newly created MATLAB arrays. It uses the mxGet* functions to extract your data from your input arguments prhs[0] and prhs[0]. Finally, it calls your computational routine, passing the input and output data pointers as function parameters.
MATLAB assigns plhs[0] to C and plhs[1] to D.
C MEX Cycle

Look at the example, yprime.c, found in your matlabroot/extern/examples/mex/ folder. (Building MEX-Files explains how to create the binary MEX-file.) Its calling syntax is [YP] = YPRIME(T,Y), where T is an integer and Y is a vector with four elements. For T=1 and Y=1:4, when you type:
yprime(T,Y)
MATLAB displays:
ans =
2.0000 8.9685 4.0000 -1.0947
The gateway routine validates the input arguments. This step includes checking the number, type, and size of the input arrays as well as examining the number of output arrays. If the inputs are not valid, call mexErrMsgTxt. For example:
/* Check for proper number of arguments */
if (nrhs != 2) {
mexErrMsgTxt("Two input arguments required.");
} else if (nlhs > 1) {
mexErrMsgTxt("Too many output arguments.");
}
/* Check the dimensions of Y. Y can be 4 X 1 or 1 X 4. */
m = mxGetM(Y_IN);
n = mxGetN(Y_IN);
if (!mxIsDouble(Y_IN) || mxIsComplex(Y_IN) ||
(MAX(m,n) != 4) || (MIN(m,n) != 1)) {
mexErrMsgTxt("YPRIME requires that Y be a 4 x 1 vector.");
}
To create MATLAB arrays, call any of the mxCreate* functions, like mxCreateDoubleMatrix, mxCreateSparse, or mxCreateString. If it needs them, the gateway routine can call mxCalloc to allocate temporary work arrays for the computational routine. In this example:
/* Create a matrix for the return argument */ plhs[0] = mxCreateDoubleMatrix(m, n, mxREAL);
In the gateway routine, you access the data in mxArray and manipulate it in your computational subroutine. For example, the expression mxGetPr(prhs[0]) returns a pointer of type double * to the real data in the mxArray pointed to by prhs[0]. You can then use this pointer like any other pointer of type double * in C. For example,
/* Assign pointers to the various parameters */ yp = mxGetPr(plhs[0]);
In this example, a computational routine, yprime, performs the calculations:
/* Do the actual computations in a subroutine */ yprime(yp,t,y);
After calling your computational routine from the gateway, you can set a pointer of type mxArray to the data it returns. MATLAB recognizes the output from your computational routine as the output from the binary MEX-file.
When a binary MEX-file completes its task, it returns control to MATLAB. MATLAB automatically destroys any arrays created by the MEX-file not returned through the left-hand side arguments.
In general, we recommend that MEX-file functions destroy their own temporary arrays and free their own dynamically allocated memory. It is more efficient to perform this cleanup in the source MEX-file than to rely on the automatic mechanism.
MEX-files support all C++ language standards.
This section discusses specific C++ language issues to consider when creating and using MEX-files.
The C++ source code for the examples provided by MATLAB use the .cpp file extension. The extension .cpp is unambiguous and generally recognized by C++ compilers. Other possible extensions include .C, .cc, and .cxx.
For information on using C++ features, see Technical Note 1605, MEX-files Guide, at http://www.mathworks.com/support/tech-notes/1600/1605.html. Look for the sections under the "C++ Mex-files" heading.
You can run a C++ MEX-file only on systems with the same version of MATLAB that the file was compiled on.
Use mex –setup to select a C++ compiler, then type:
mex filename.cpp
You can use command-line options, as shown in the MEX Script Switches table.
Your link command must have all the necessary DLL files that the MEX-function is dependent upon. To help you check for dependent files, see the Troubleshooting topic DLL Files Not on Path on Microsoft Windows Systems.
The examples Using C++ Features in MEX-Files and File Handling with C++ illustrate the use of C++ by walking through source code examples available in your MATLAB folder.
Do not use the mxFree or mxDestroyArray functions in a C++ destructor of a class used in a MEX-function. If the MEX-function throws an error, MATLAB cleans up MEX-file variables, as described in Automatic Cleanup of Temporary Arrays.
If an error occurs that causes the object to go out of scope, MATLAB calls the C++ destructor. Freeing memory directly in the destructor means both MATLAB and the destructor free the same memory, which can corrupt memory.
Using cout or the C-language printf function does not work as expected in C++ MEX-files. Use the mexPrintf function instead.
![]() | Creating C Language MEX-Files | Examples of C Source MEX-Files | ![]() |

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.
| © 1984-2009- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |