仿真过程后​​将变量从 .cpp 文件传输到 Matlab 工作区

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

我目前在带有 R2015b 的 Matlab 中使用名为 Policy Search toolbox 的工具箱。我 "mexed" 所有文件和工具箱工作正常。 计算微分方程的 .cpp 文件之一,在 Matlab 中的一个函数中计算并使用一个值。 由于工具箱与数据管理器一起工作,我不能在模拟过程后调用变量。 由于该函数是工具箱的巨大 (!) 构造的一部分,我不能只修改输出或复制粘贴并在别处调用该函数。

#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);

}

如何将 YDD(底部的计算值)从那里移到我的 Matlab 工作区中? C++ 中有一种 "public goto workspace as output plz!" 函数吗?

非常感谢您的帮助!

如果 Ydd 是一个 double * 数组,大小为 nYdd(您需要知道),那么您可以使用指针 plhs 将其分配给输出].

代码将读作:

//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);

我猜你可以写一个函数为

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

上面有这个,但可能不需要 ;)

文档: