Matlab Tricks

How to export to, and store in, the Matlab workspace scalar, vector, and matrix variables from inside C/C++ S-Functions

Certainly this part of Matlab's features is not the most well-documented thing in the world, and accordingly it took me quite some time with the good old trial-and-error approach to figure out exactly what to call when in which order. The solution might not be the most elegant, but it works, and since everyone I know usually restricts himself to a workaround (printf in the S-Function or writing to a text file), I believe it's worth sharing.

  mxArray *mexArray;
  double *mexData;

  double yourScalarValue;
  double *yourVector;
  double *yourMatrix; /* here, I assume this to be stored in 1D,
                         but you can use a 2D array as well */

  int i;

  #define M (4);
  #define N (4);

  /* all your other initializations, etc. */

  /********** a scalar variable ****************************/
  mexArray = mxCreateNumericMatrix(0, 0, mxDOUBLE_CLASS, mxREAL);
  mexData  = mxMalloc(1 * sizeof(double));
  mexData[0] = yourScalarValue;
  mxSetPr(mexArray, mexData);
  mxSetM(mexArray, (mwSize)1);
  mxSetN(mexArray, (mwSize)1);
  mexPutVariable("caller", "scalarValueNameInMatlab", mexArray);
  mxDestroyArray(mexArray);


  /********** a vector ************************************/
  mexArray = mxCreateNumericMatrix(0, 0, mxDOUBLE_CLASS, mxREAL);
  mexData  = mxMalloc(M * sizeof(double));
  for ( i = 0; i < M; i++ ) {
      mexData[i] = yourVector[i];
  }
  mxSetPr(mexArray, mexData);
  mxSetM(mexArray, (mwSize)M); /* assuming the vector is 4x1 */
  mxSetN(mexArray, (mwSize)1);
  mexPutVariable("caller", "vectorNameInMatlab", mexArray);
  mxDestroyArray(mexArray);


  /********** a 2D matrix **********************************/
  mexArray = mxCreateNumericMatrix(0, 0, mxDOUBLE_CLASS, mxREAL);
  mexData  = mxMalloc(M*N * sizeof(double));
  for ( i = 0; i < M*N; i++ ) {
      mexData[i] = q_fxu_u_u_[i];
  }
  mxSetPr(mexArray, mexData);
  mxSetM(mexArray, (mwSize)M); /* assuming the matrix is 4x4 */
  mxSetN(mexArray, (mwSize)N);
  mexPutVariable("caller", "matrixNameInMatlab", mexArray);
  mxDestroyArray(mexArray);

One thing to be kept in mind: don't forget to destroy the mex array after eacht write-out to the Matlab workspace! You'll have a huge loss of performance elswise.

Notification after successful script execution on remote machine

If called at the end of a time-consuming computation, especially when executed on a parallel computation capable remote machine, some way of notification is very helpful. Matlab provides a means of sending e-mails, which what we want here. A complete example can be found in the product help:
Matlab → Functions → Data Import and Export → Internet File Access → sendmail.