Main Content

Pass Variables from C++ toMATLAB

Ways to Pass Variables

You can pass C++ variables to MATLAB®using these techniques:

  • Pass the variables as function arguments in calls to thematlab::engine::MATLABEnginefevalorfevalAsyncmember functions. Variables passed as arguments to function calls are not stored in the MATLAB base workspace. For more information, seeCall MATLAB Functions from C++.

  • Put the variables in the MATLAB base or global workspace using thematlab::engine::MATLABEnginesetVariableandsetVariableAsyncmember functions. For more information on using global variables in MATLAB, see the MATLABglobalfunction.

You can create variables in the MATLAB workspace using thematlab::engine::MATLABEngineevalandevalAsyncmember functions. Use these functions to execute MATLAB statements that make assignments to variables. For more information, seeEvaluate MATLAB Statements from C++.

Put Variables inMATLABBase Workspace

This sample code performs these steps:

  • Puts variables in the MATLAB workspace usingMATLABEngine::setVariable

  • Uses these variables to call the MATLABmovsumfunction usingMATLABEngine::eval

  • Gets the output variableAfrom the MATLAB workspace usingMATLABEngine::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 # include“MatlabDataArray.hpp MatlabEngine.hpp" #include 
void callputVariables() { using namespace matlab::engine; // Start MATLAB engine synchronously std::unique_ptr matlabPtr = startMATLAB(); //Create MATLAB data array factory matlab::data::ArrayFactory factory; // Create variables matlab::data::TypedArray data = factory.createArray({ 1, 10 }, { 4, 8, 6, -1, -2, -3, -1, 3, 4, 5 }); matlab::data::TypedArray windowLength = factory.createScalar(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 const A = matlabPtr->getVariable(u"A"); // Display the result int i = 0; for (auto r : A) { std::cout << "results[" << i << "] = " << r << std::endl; ++i; } }

如何设置和信息构建c++缘起ne programs, seeRequirements to Build C++ Engine Programs.

See Also

|

Related Topics