Main Content

Elements of a C++ Engine Program

The MATLAB® engine API for C++ enables C++ programs to interact with MATLAB synchronously or asynchronously. Supported operations include:

  • Start MATLAB.

  • Connect to a MATLAB shared session on the local machine.

  • Call MATLAB functions with input arguments passed from C++ and output variables returned from MATLAB.

  • Evaluate MATLAB statements in the MATLAB base workspace.

  • Pass variables from C++ to MATLAB and from MATLAB to C++.

    The size of data arrays passed between C++ and MATLAB is limited to 2 GB. This limit applies to the data plus supporting information passed between the processes.

Coding Environment

The MATLAB engine API for C++ is included in the MATLAB product. For the complete API, see C++ Engine API. The API uses the MATLAB Data API for C++ to work with MATLAB data.

Before using the API, set up your build and run-time environment. For more information, see Requirements to Build C++ Engine Programs.

Coding Patterns

This example shows how to write C++ code to execute the equivalent of these MATLAB statements.

A = [4 8 6 -1 -2 -3 -1 3 4 5];
M = movsum(A,3,"Endpoints","discard");

This C++ code passes a vector of data arrays to the MATLAB movsum function and returns the result.

 C++ Engine Code

Include Header Files

Add header files for the MATLAB engine and MATLAB data arrays.

#include "MatlabEngine.hpp"
#include "MatlabDataArray.hpp"

Start MATLAB Session

Start a MATLAB session and get a unique pointer to the instance.

std::unique_ptr<MATLABEngine> matlabPtr = startMATLAB();

Create MATLAB Data Array

Create a MATLAB data array factory to construct the data types used by the matlab::engine::MATLABEngine member functions.

matlab::data::ArrayFactory factory;

Initialize Data Arrays

Create a vector of MATLAB data arrays for the input arguments of the MATLAB function. Each argument is an array in the vector.

// Create a vector of MATLAB data arrays for arguments    
std::vector<matlab::data::Array> args({
    factory.createArray<double>({ 1, 10 }, { 4, 8, 6, -1, -2, -3, -1, 3, 4, 5 }),

Call MATLAB Function and Return Result

Call the MATLAB movsum function with input arguments using the MATLABEngine::feval member function. Define the returned result as a MATLAB data array of type double.

// Call MATLAB function with arguments and return results
matlab::data::TypedArray<double> result = matlabPtr->feval(u"movsum", args);

See Also


Related Topics