Pass Variables from C++ to MATLAB - MATLAB & Simulink (original) (raw)

Main Content

Ways to Pass Variables

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

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:

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

matlab::engine::MATLABEngine | matlab::engine::startMATLAB

Topics