You can 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++.
This sample code 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 auto data = factory.createArray<double>({ 1, 10 }, { 4, 8, 6, -1, -2, -3, -1, 3, 4, 5 }); auto windowLength = factory.createScalar<int32_t>(3); auto name = factory.createCharArray("Endpoints"); auto value = factory.createCharArray("discard"); // Put variables in the MATLAB workspace matlabPtr->setVariable(convertUTF8StringToUTF16String("data"), std::move(data)); matlabPtr->setVariable(convertUTF8StringToUTF16String("w"), std::move(windowLength)); matlabPtr->setVariable(convertUTF8StringToUTF16String("n"), std::move(name)); matlabPtr->setVariable(convertUTF8StringToUTF16String("v"), std::move(value)); // Call the MATLAB movsum function matlabPtr->eval(convertUTF8StringToUTF16String("A = movsum(data, w, n, v);")); // Get the result matlab::data::TypedArray<double> const A = matlabPtr-> getVariable(convertUTF8StringToUTF16String("A")); // Display the result int i = 0; for (auto r : A) { std::cout << "results[" << i << "] = " << r << std::endl; ++i; } }
matlab::engine::MATLABEngine
| matlab::engine::convertUTF8StringToUTF16String
| matlab::engine::startMATLAB