Main Content

CallMATLABFunctions from MEX Functions

Call MATLAB®functions from MEX functions using thematlab::engine::MATLABEngine::fevalfunction.fevalenables 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 thematlab::data::ArrayFactoryand theC++ Engine API.

matlab::data::ArrayFactory factory; std::shared_ptr matlabPtr = getEngine();

Single Output

This example calls the MATLABsqrtfunction with the following inputs:

  • The function name, passed as a UTF16 string

  • The inputs to thesqrtfunction, specified as amatlab::data::Array

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

The example moves the returned value to amatlab::data::TypedArray, which provides iterators used in the range-basedforloop that creates an array of typedoublefrom the results returned by the MATLABsqrtfunction.

// Define input and output argumentsmatlab::data::Array args({ factory.createArray({ 1, 4 },{ 1, 2, 3, 4 }) }); matlab::data::Array result;// Call feval and return 1 argumentresult = matlabPtr->feval(u"sqrt", args); matlab::data::TypedArray returnedValues(std::move(result));// Create native arraydouble dataArray[4]; int i = 0; for (auto elem : returnedValues) { dataArray[i] = elem; i++; }

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 MATLABgcdfunction with the following inputs:

  • The function name passed as a UTF16 string

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

  • The inputs to thegcdfunction, specified as astd::vectorofmatlab::data::Arrayelements.

The returned value is astd::vectorcontaining threematlab::data::Arrayelements.

// Define argumentsstd::vector args({ factory.createScalar(30), factory.createScalar(56)}); const size_t numReturned = 3; std::vector result;// Call feval and return 3 argumentsresult = matlabPtr->feval(u"gcd", numReturned, args);

See Also

Related Topics