Introduction to Engine API for C++

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 MATLAB Engine API for C++ is included in the MATLAB product. For the complete API, see C++ Engine API.

Getting Started

The MATLAB Engine API for C++ comprises a set of C++ header files and C runtime shared libraries. The namespace matlab::engine contains several utility functions and a set of C++ classes.

Begin using the MATLAB Engine API for C++ by setting up your build and runtime environment. Ensure that you have a supported compiler installed. Use the MATLAB mex command to setup your environment and to build C++ applications. You can also configure your IDE to build C++ applications that use the Engine API. For information on how to do this, see Build C++ Engine Programs.

The Engine API supports the use of the MATLAB Data API. This API provides a way for applications running outside of MATLAB to work with MATLAB data. For more information on this API, see MATLAB Data API.

Basic Elements of C++ Engine Programs

Here is some simple C++ engine code showing the basic elements used to execute a MATLAB command. This code passes a vector of data arrays to a MATLAB function, movsum, and returns the result. This C++ code executes the equivalent of these statements in MATLAB.

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

Basic Elements of C++ Engine Code

Add header files for MATLAB engine and MATLAB data arrays.

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

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

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

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

matlab::data::ArrayFactory factory;

Define a vector of MATLAB data arrays for the input arguments to 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 }),
    factory.createScalar<int32_t>(3),
    factory.createCharArray("Endpoints"),
    factory.createCharArray("discard")
});

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

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

See Also

|

Related Topics