Search code examples
c++matlabmex

Transfer a variable from .cpp file to Matlab workspace after simulation process


I am currently using a toolbox called Policy Search toolbox in Matlab with R2015b. I "mexed" all files and the toolbox works just fine. One of the .cpp files calculating a differential equation, a value is computed and used in one of the functions back in Matlab. As the toolbox is working with a data manager, I can not just call the variable after the simulation process. As the function is part of a giantic (!) construct of the toolbox I can not just modify the output or copy and paste and call the function elsewhere.

#include "mex.h"
#include <math.h>


void mexFunction(int nlhs, mxArray *plhs[], 
             int nrhs, const mxArray *prhs[])
{
     // Input
double
*startPosition      = mxGetPr(prhs[0]),

.......// some more variables ...

       // Output
plhs[0] = mxCreateDoubleMatrix(numJoints, numTrajectorySteps, mxREAL);
plhs[1] = mxCreateDoubleMatrix(numJoints, numTrajectorySteps, mxREAL);
plhs[2] = mxCreateDoubleMatrix(numJoints, numTrajectorySteps, mxREAL);

double
*Y = mxGetPr(plhs[0]),
*Yd = mxGetPr(plhs[1]),
*Ydd = mxGetPr(plhs[2]);

 .......// some more code ...

        double smoothedForcingFunction = iTrajectoryStep < numForcedSteps ?       forcingFunction[oldI] : 0;
        double Ydd = (alpha_x*(beta_x*(goalTemp-Y[oldI])+(goalVel-Yd[oldI])/ tau)  +(amplitude[iJoint]*smoothedForcingFunction))*tau * tau;

        // simplectic Euler
        Yd[curI] = Yd[oldI] + dt*Ydd;
        Y[curI] = Y[oldI] + dt*Yd[curI];

    }        
}
//    printf("Done\n");
    mxDestroyArray(xData);
    mxDestroyArray(xdData);
    mxDestroyArray(tData);

}

How can I get YDD (the calculated one on the bottom) out of there into my Matlab workspace? Is there a kind of "public goto workspace as output plz!" function in C++ ?

Thanks so much for your help!


Solution

  • If Ydd is a double * array, of size nYdd (that you need to know), then you can assign it to the output using the pointer plhs.

    The code would read as:

    //Note that this is for output n1. If you want to output more things use plhs[1], plhs[2],...
    
    // Allocate memory for the output:
    // It is 1 dimensional, with nYdd elements, double type and real numbers only
    plhs[0] = mxCreateNumericArray(1,nYdd, mxDOUBLE_CLASS, mxREAL);
    // Get the pointer into your own variable
    double *mxYdd =(double*) mxGetPr(plhs[0]);
    // copy whateer is in Ydd into mxYdd
    memcpy(mxYdd ,Ydd,nYdd*sizeof(double));
    // delete Ydd (its already copyed
    free(Ydd);
    

    I guess you could write a function as

    void public_goto_workspace_as_output_plz(mxArray* plhs,double* Ydd, size_t nYdd);
    

    with this on it, but probably not needed ;)

    Docs: