Main Content

Start MATLAB Sessions from C++

These examples show how to start a MATLAB® engine session from your C++ program synchronously or asynchronously. To start the session, use one of these utility functions, which are defined in the matlab::engine namespace:

For information on how to setup and build C++ engine programs, see Requirements to Build C++ Engine Applications.

Start MATLAB Session Synchronously

Start MATLAB from C++ synchronously. startMATLAB returns a unique pointer to the MATLABEngine instance.

#include "MatlabEngine.hpp"

void startMLSession() {
    using namespace matlab::engine;

    // Start MATLAB engine synchronously
    std::unique_ptr<MATLABEngine> matlabPtr = startMATLAB();
}

Start MATLAB Session Asynchronously

Start MATLAB from C++ asynchronously. Use FutureResult::get to get the unique pointer to the MATLABEngine instance that is returned by startMATLABAsync.

#include "MatlabEngine.hpp"

void startMLSessionAsync() {
    using namespace matlab::engine;

    // Start MATLAB engine asynchronously
    FutureResult<std::unique_ptr<MATLABEngine>> matlabFuture = startMATLABAsync();
    std::unique_ptr<MATLABEngine> matlabPtr = matlabFuture.get();
}

Start MATLAB with Startup Options

You can start a MATLAB session using supported MATLAB startup options. For information on MATLAB startup options, see Commonly Used Startup Options. For information on the startup options supported by the engine, see matlab::engine::MATLABEngine.

This example starts MATLAB using the -r and matlab.engine.ShareEngine options. Create a vector containing each option as an element in the vector.

#include "MatlabEngine.hpp"

void startMLOptions() {
    using namespace matlab::engine;

    // Start MATLAB with -r option
    std::vector<String> optionVec;
    optionVec.push_back(u"-r");
    optionVec.push_back(u"matlab.engine.shareEngine");
    std::unique_ptr<MATLABEngine> matlabPtr = startMATLAB(optionVec);
}

See Also

|

Related Topics