MATLAB and C++ Automatic coupling

3 Ansichten (letzte 30 Tage)
Yahia Alabbasi
Yahia Alabbasi am 22 Apr. 2018
Beantwortet: Madheswaran am 31 Mai 2025
Hi support,
I would like to develop an automatic coupling between C++ and MATLAB .
In simple Word:
  • - Import in C++ the data from a .mat file
  • - Run the simulation in C++
  • - Export the results back in a .mat file
Based on the above details of my case, could you advise me for a way to start with?
Please let me know if you require any further clarifications.
Thank you for your continuous support.
Yahia Alabbasi B.C.Eng (Hons) Research Assistant- Qatar University-Department of Civil and Architectural Engineering

Antworten (1)

Madheswaran
Madheswaran am 31 Mai 2025
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:
  1. https://mathworks.com/help/matlab/matlab-c-api-to-read-mat-file-data.
  2. https://mathworks.com/help/matlab/cc-mx-matrix-library.
  3. https://mathworks.com/help/matlab/matlab_external/creating-a-mat-file-in-c.html
Hope this helps!

Kategorien

Mehr zu Call C++ from MATLAB finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by