This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English verison of the page.

Note: This page has been translated by MathWorks. Please click here
To view all translated materals including this page, select Japan from the country navigator on the bottom of this page.

mexFunction (C and Fortran)

Entry point to C/C++ or Fortran MEX file

C Syntax

#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, 
  const mxArray *prhs[])

Fortran Syntax

#include "fintrf.h"
subroutine mexFunction(nlhs, plhs, nrhs, prhs)
integer nlhs, nrhs
mwPointer plhs(*), prhs(*)



Number of expected output mxArrays


Array of pointers to the expected output mxArrays


Number of input mxArrays


Array of pointers to the input mxArrays. Do not modify any prhs values in your MEX file. Changing the data in these read-only mxArrays can produce undesired side effects.


mexFunction is not a routine you call. Rather, mexFunction is the name of the gateway function in C (subroutine in Fortran) which every MEX file requires. When you invoke a MEX function, MATLAB® software finds and loads the corresponding MEX file of the same name. MATLAB then searches for a symbol named mexFunction within the MEX file. If it finds one, it calls the MEX function using the address of the mexFunction symbol. MATLAB displays an error message if it cannot find a routine named mexFunction inside the MEX file.

When you invoke a MEX file, MATLAB automatically seeds nlhs, plhs, nrhs, and prhs with the calling arguments. In the syntax of the MATLAB language, functions have the general form:

[a,b,c,...] = fun(d,e,f,...)

where the ... denotes more items of the same format. The a,b,c... are left-side output arguments, and the d,e,f... are right-side input arguments. The arguments nlhs and nrhs contain the number of left side and right side arguments, respectively. prhs is an array of mxArray pointers whose length is nrhs. plhs is an array whose length is nlhs, where your function must set pointers for the output mxArrays.


It is possible to return an output value even if nlhs = 0, which corresponds to returning the result in the ans variable.

To experiment with passing input arguments, build the mexfunction.c example, following the instructions in Table of MEX File Source Code Files.


See the following examples in matlabroot/extern/examples/mex.

See Also

Introduced before R2006a

Was this topic helpful?