MATLAB Language Introduction to MEX API Check number of inputs/outputs in a C++ MEX-file


In this example we will write a basic program that checks the number of inputs and outputs passed to a MEX-function.

As a starting point, we need to create a C++ file implementing the "MEX gateway". This is the function executed when the file is called from MATLAB.


// MathWorks provided header file
#include "mex.h"

// gateway function
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
    // This function will error if number of inputs its not 3 or 4
    // This function will error if number of outputs is more than 1

    // Check inputs:
    if (nrhs < 3 || nrhs > 4) {
            "Invalid number of inputs to MEX file.");

    // Check outputs:
    if (nlhs > 1) {
                "Invalid number of outputs to MEX file.");

First, we include the mex.h header which contains definitions of all the required functions and data types to work with the MEX API. Then we implement the function mexFunction as shown, where its signature must not change, independent of the inputs/outputs actually used. The function parameters are as follows:

  • nlhs: Number of outputs requested.
  • *plhs[]: Array containing all the outputs in MEX API format.
  • nrhs: Number of inputs passed.
  • *prhs[]: Array containing all the inputs in MEX API format.

Next, we check the number of inputs/outputs arguments, and if the validation fails, an error is thrown using mexErrMsgIdAndTxt function (it expects somename:iD format identifier, a simple "ID" won't work).

Once the file is compiled as mex testinputs.cpp, the function can be called in MATLAB as:

>> testinputs(2,3)
Error using testinputs. Invalid number of inputs to MEX file.

>> testinputs(2,3,5)

>> [~,~] = testinputs(2,3,3)
Error using testinputs. Invalid number of outputs to MEX file.