I write a C++ program whose only purpose is to call Matlab code. I have a main routine, which
read data in a file (matrices with high dimension 90000*24) into C++ structures
pass these structures to Matlab code
launch the Matlab routine with these structures in argument
get the output data from Matlab and store them in C++ structures
In 2/, matrices are fields in a Matlab struct. The struct, say MATLAB_STRUCT
has several matrix fields, MATLAB_STRUCT.Z1
, MATLAB_STRUCT.Z2
,... and some float fields MATLAB_STRUCT.flt1
,...
What is the correct approach to set C++ matrices (double**
) as the fields of the Matlab struct? So far, I came up with this, using engine.h
mxArray* labcoeffs_array = convertVectorToMxArray(labcoeffs,
coeff_nrows, coeff_ncols);
const std::string lab_coeff_name = "MATLAB_STRUCT.labCoef";
engPutVariable(ep, lab_coeff_name.c_str(), labcoeffs_array);
where convertVectorToMxArray
is an helper I wrote to convert double**
to a mxArray
,
inline mxArray *convertVectorToMxArray(double** mat,
const int nb_rows, const int nb_cols)
{
mxArray *outputMxArray = mxCreateDoubleMatrix(
(int) nb_rows,
(int) nb_cols,
mxREAL);
double *data = (double*) mxGetData(outputMxArray);
for (int r = 0; r < nb_rows; r++)
for (int c = 0; c < nb_cols; c++)
data[r + c*nb_rows] = (double)mat[r][c];
return outputMxArray;
};
But I have seen some other technique for assigning a value to a Matlab struct in the Cpp code (a float value though, not a matrix), imitating the command line syntax in a C++ string:
std::string setStruct = "MATLAB_STRUCT" + "." + "nB" + " = " + str->nB + ";";
matlabExecute(ep, setStruct);
with ep
a pointer to a Matlab engine.
Is it possible to adapt this approach with command line to assigning a value to a matrix type field of a Matlab struct?
what is the best approach to assign a value to a matrix type field of a Matlab struct?