Main Content

Pass Variables from C++ to MATLAB

Ways to Pass Variables

These examples show you how to pass C++ variables to MATLAB® using these techniques:

  • Pass the variables as function arguments in calls to the matlab::engine::MATLABEngine feval or fevalAsync member functions. Variables passed as arguments to function calls are not stored in the MATLAB base workspace. For more information, see Call MATLAB Functions from C++.

  • Put the variables in the MATLAB base or global workspace using the matlab::engine::MATLABEngine setVariable and setVariableAsync member functions. For more information on using global variables in MATLAB, see the MATLAB global function.

You can create variables in the MATLAB workspace using the matlab::engine::MATLABEngine eval and evalAsync member functions. Use these functions to execute MATLAB statements that make assignments to variables. For more information, see Evaluate MATLAB Statements from C++.

Put Variables in MATLAB Base Workspace

This example performs these steps:

  • Puts variables in the MATLAB workspace using MATLABEngine::setVariable

  • Uses these variables to call the MATLAB movsum function using MATLABEngine::eval

  • Gets the output variable A from the MATLAB workspace using MATLABEngine::getVariable.

Here is the equivalent MATLAB code.

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

Here is the C++ code.

#include "MatlabDataArray.hpp"
#include "MatlabEngine.hpp"
#include <iostream>

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

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

    //Create MATLAB data array factory
    matlab::data::ArrayFactory factory;

    // Create variables    
    matlab::data::TypedArray<double> data = factory.createArray<double>({ 1, 10 },
        { 4, 8, 6, -1, -2, -3, -1, 3, 4, 5 });
    matlab::data::TypedArray<int32_t>  windowLength = factory.createScalar<int32_t>(3);
    matlab::data::CharArray name = factory.createCharArray("Endpoints");
    matlab::data::CharArray value = factory.createCharArray("discard");
      
    // Put variables in the MATLAB workspace
    matlabPtr->setVariable(u"data", std::move(data));
    matlabPtr->setVariable(u"w", std::move(windowLength));
    matlabPtr->setVariable(u"n", std::move(name));
    matlabPtr->setVariable(u"v", std::move(value));

    // Call the MATLAB movsum function
    matlabPtr->eval(u"A = movsum(data, w, n, v);");

    // Get the result
    matlab::data::TypedArray<double> const A = matlabPtr->getVariable(u"A");
      
    // Display the result
    int i = 0;
    for (auto r : A) {
        std::cout << "results[" << i << "] = " << r << std::endl;
        ++i;
    }
}

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

See Also

|

Related Topics