Hi Yahia,
You can achieve automatic coupling between C++ and MATLAB using the MAT-File API to read and write MAT files directly from C/C++. Here is a simple workflow you can follow:
// Read data from input MAT file
#include "mat.h"
MATFile *input_file = matOpen("data_input.mat", "r");
if (input_file == NULL) {
printf("Error opening input file\n");
return -1;
}
mxArray *data_array = matGetVariable(input_file, "data_array");
if (data_array == NULL) {
printf("Error reading variable\n");
matClose(input_file);
return -1;
}
matClose(input_file);
// ...Your simulation/processing work goes here...
// Save processed data to data_output.mat
MATFile *output_file = matOpen("data_output.mat", "w");
if (output_file == NULL) {
printf("Error creating output file\n");
mxDestroyArray(data_array);
return -1;
}
int status = matPutVariable(output_file, "data_array", data_array);
if (status != 0) {
printf("Error writing variable\n");
}
matClose(output_file);
mxDestroyArray(data_array);
Please note that the MAT-File API has limited class support, as it doesn't accommodate MATLAB objects from user-defined classes, and it lacks thread safety, meaning its functions can only be used on a single thread at a time to avoid issues, as mentioned here: https://mathworks.com/help/matlab/matlab_external/custom-applications-to-read-and-write-mat-files.html
If you need to work with user-defined classes, you can explore the MATLAB Engine API for C++. The Engine API allows you to start MATLAB sessions, call MATLAB functions directly, handle user-defined classes, and execute MATLAB commands from within your C++ application.
For more detailed information, please refer to the following documentations:
- https://mathworks.com/help/matlab/matlab-c-api-to-read-mat-file-data.
- https://mathworks.com/help/matlab/cc-mx-matrix-library.
- https://mathworks.com/help/matlab/matlab_external/creating-a-mat-file-in-c.html
Hope this helps!
