The Basics
Compiled functions (aka 'mex' functions, short for "m-file, executable") allow MATLAB users to combine the efficiency and performance characteristics of C/FORTRAN with the ease-of-use inherent to MATLAB. Mex functions are easy to compile: the command to do this can be issued directly from the MATLAB interpreter itself.
A common use pattern for mex functions involves profiling an all-MATLAB codebase, determining which parts require the most runtime, and recoding those parts in a compiled language such as C or FORTRAN to improve the overall efficiency of the codebase. It's not advisable to start programming in MATLAB with mex functions: the built-in MATLAB routines are quite extensive (and fairly efficient, especially for e.g. linear algebra operations) and often "good enough" at least for prototyping most types of scientific code.
File: HelloWorld.c
This example assumes that the low-level code is written in C, but writing mex functions in FORTRAN is also possible. Additionally, since C is often the lingua franca for FFIs (Foreign Function Interfaces), most languages that have a C FFI could also communicate with MATLAB through MATLAB's C FFI (i.e. Mex functions). As with scripts and MATLAB functions, the name of the C file, "HelloWorld.c", determines the name of the function as it will be called from the MATLAB interpreter (again, minus the .c extension).
#include
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
printf("Hello World\n");
}
Every mex file must include the "mex.h" header file (
Each mex file can also only contain a single function,
and this function must be named "mexFunction" (