c++matlabmatlab-engine

matlab engine data retrieval fails


I have a problem reading out data from the matlab engine. I can create a variable in the
engine, and saving the workspace and subsequently loading it into matlab shows that the variable exists and has the right value.
However the C++ value that I retrieve is always zero, no matter what the real value is. The pointer to the variable that I receive (matM) is a valid pointer. If the 'engGetVariable' command fails, it should be NULL according to the Matlab documentation.
Yet, trying the matlab command to retreive integer data from this pointer (mxGetData) yields zero, when the value of the variable should be 5. Also directly checking the value belonging to the pointer yields zero.

Below is the code:

int main()
{
Engine *ep;
mxArray *matM = NULL;

if (!(ep = engOpen("")))
{
  fprintf(stderr, "\nCan't start MATLAB engine\n");
  return EXIT_FAILURE;
}

engEvalString(ep, "m = 5");
engEvalString(ep, "save 'MatlabTestsResult.mat'");

matM = engGetVariable(ep,"m");
if (matM==NULL){cout << "pointer is null..." << endl;}

int* Cm = (int *)mxGetData(matM);
cout << *Cm << endl;

cout << "Pointer: " << matM << endl;
int tst = *((int*) matM);
cout << tst  << endl;


mxDestroyArray(matM);
engClose(ep);

return EXIT_SUCCESS;
}

and the output it creates:

./MatlabTests  
0  
Pointer: 0x7f25559b7f90  
0  

I can't find what I am doing different to the matlab examples ( http://www.mathworks.co.uk/help/matlab/apiref/mxgetdata.html , http://www.mathworks.co.uk/help/matlab/apiref/enggetvariable.html?searchHighlight=engGetVariable ) that causes the variable readout to fail.


Solution

  • The return value from mxGetData should be cast to a double* I imagine, then you should be able to dereference it to get 5.0. By default Matlab numbers are doubles, so m = 5 does not assign an int to m.