MEX Applications

You can call your own C, C++, or Fortran programs from the MATLAB® command line as if they were built-in functions. These programs are called MEX functions. To create a MEX function, write your program using MATLAB APIs, then build using the mex command. The APIs provide these features:

  • Get inputs from MATLAB

  • Return results to MATLAB

  • Support MATLAB data types

  • Call MATLAB functions from the MEX function.

  • Integrate seamlessly into MATLAB

MATLAB supports MEX functions written in C, C++, or Fortran.

Writing C Language MEX Functions

As of MATLAB R2018a, there are two choices for building C/C++ MEX functions. MEX source files written with the MATLAB Data API use C++11 programming features, but are supported by MATLAB R2018a and later. If your MEX files must run in MATLAB R2017b or earlier, then write source files using functions in the C Matrix API.

If you do not need MEX files that work in R2017b and you are familiar with modern C++, consider using the new C++ MEX API and MATLAB Data API. These APIs provide better type safety, array bounds checking, and support for modern C++ constructs to simplify coding. If you are more comfortable working in the C language, continue using the C MEX API and C Matrix API.

Caution

Do not mix functions in different APIs. For example, do not use functions in the C Matrix API with functions in the MATLAB Data API.

MEX Functions Using C++ Programming Features

To use C++11 programming features, see:

MEX Functions Based on the C Matrix API

To write MEX functions based on the mxArray data type, which is defined in the C Matrix API, see:

Writing Fortran MEX Functions

To write Fortran MEX functions, see:

MATLAB does not support the interleaved complex API for Fortran MEX functions.

Related Topics