- Check the MATLAB Workspace: After transferring the data, check if the variable is in the MATLAB workspace. You can use the “engEvalString” function to execute MATLAB commands from your C++ program.
- Visibility in MATLAB Workspace: If the variables are not visible in the MATLAB workspace after the program ends, it might be because MATLAB Engine sessions are separate from the MATLAB desktop session. The variables exist only for the duration of the engine session.
- Save Variables to MAT-File: If you need to retain the variables in MATLAB after the C++ program has finished executing, consider saving them to a MAT-file. You can then load this MAT-file in MATLAB to access the variables.
- Debugging: If the variables still do not appear, check for errors in data transfer and ensure that “engPutVariable” is called successfully. You can also use “engOutputBuffer” to capture any error messages from MATLAB.
Why no data transfer between c++ and MATLAB Workspace?
4 views (last 30 days)
Show older comments
I am trying to transfer variables from C++ to the MATLAB workspace. The program compiles successfully, and I get the correct results back, but the variables are not visible in the MATLAB workspace.
Here is my C++ code:
#include "MatlabDataArray.hpp"
#include "MatlabEngine.hpp"
#include <iostream>
#include <windows.h>
int main() {
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;
}
}
Used Software:
- VS Code 1.94.2
- Compiler: mingw81
- MATLAB: R2022a
0 Comments
Answers (1)
Jaimin
on 7 Nov 2024
Hello @Kreilinger
These steps and tips can help you troubleshoot and ensure that variables are visible in the MATLAB workspace:
Kindly refer following MathWorks Documentation for more information.
I hope this will be helpful.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!