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 the
matlab::engine::MATLABEngine
fevalorfevalAsyncmember 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 the
matlab::engine::MATLABEngine
setVariableandsetVariableAsyncmember functions. For more information on using global variables in MATLAB, see the MATLABglobal
function.
You can create variables in the MATLAB workspace using thematlab::engine::MATLABEngine
evalandevalAsyncmember 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 using
MATLABEngine::setVariable
Uses these variables to call the MATLAB
movsum
function usingMATLABEngine::eval
Gets the output variable
A
from 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_ptrmatlabPtr = 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
matlab::engine::MATLABEngine
|matlab::engine::startMATLAB