Main Content

Call MATLAB Functions from MEX Functions

Call MATLAB® functions from MEX functions using the feval function. feval enables you to pass arguments from MEX functions to MATLAB functions and to return the results to the MEX function.

The following code snippets require these definitions to use matlab::data::ArrayFactory and matlab::engine::MATLABEngine.

matlab::data::ArrayFactory factory;
std::shared_ptr<matlab::engine::MATLABEngine> matlabPtr = getEngine();

Single Output

This example calls the MATLAB sqrt function with the following inputs:

  • The function name, passed as a UTF16 string

  • The inputs to the sqrt function, specified as a matlab::data::Array

The value returned to the MEX function is a four-element matlab::data::Array containing the square root of each element of the input array.

The example moves the returned value to a matlab::data::TypedArray, which provides iterators used in the range-based for loop that creates an array of type double from the results returned by the MATLAB sqrt function.

// Define input and output arguments
matlab::data::Array args({
    factory.createArray<double>({ 1, 4 },{ 1, 2, 3, 4 }) });
matlab::data::Array result;

// Call feval and return 1 argument
result = matlabPtr->feval(u"sqrt", args);
matlab::data::TypedArray<double> returnedValues(std::move(result));

// Create native array
double dataArray[4];
int i = 0;
for (auto elem : returnedValues) {
    dataArray[i] = elem;

Multiple Outputs

Some MATLAB functions return different numbers of outputs depending on how you call the function. You can specify the number of returned arguments when calling a MATLAB function from a MEX function.

This code calls the MATLAB gcd function with the following inputs:

  • The function name passed as a UTF16 string

  • The number of outputs returned by the MATLAB function, specified as a const size_t.

  • The inputs to the gcd function, specified as a std::vector of matlab::data::Array elements.

The returned value is a std::vector containing three matlab::data::Array elements.

// Define arguments
std::vector<matlab::data::Array> args({
const size_t numReturned = 3;
std::vector<matlab::data::Array> result;

// Call feval and return 3 arguments
result = matlabPtr->feval(u"gcd", numReturned, args);

See Also

Related Topics