繁体   English   中英

如何从MATLAB mex函数播种并调用C ++随机数生成器?

[英]How can I seed and call C++ random number generator from MATLAB mex function?

我正在尝试从Matlab调用随机数生成器代码(用C ++编写)。 我找到了如何编写简单的mex函数的示例。 我要编程以运行的方式是:

  1. 首先打电话设定种子。
  2. 然后后续通话将继续返回随机数。

我了解而不是多次调用,只调用一次mex函数会更有效,但是我正在尝试实现上述的步骤1和步骤2。

本质上,我的自定义随机数生成器的行为类似于Matlab随机数生成器。 有人可以给我一些有关如何实现这一目标的指示吗?

这是一个简化的示例:

myrand.cpp

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

static bool initialized = false;

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    if (nrhs != 1 || nlhs > 1)
        mexErrMsgIdAndTxt("mex:error", "Wrong number of arguments.");
    if (!mxIsDouble(prhs[0]) || mxGetNumberOfElements(prhs[0])!=1)
        mexErrMsgIdAndTxt("mex:error", "Expecting a scalar.");
    double in = mxGetScalar(prhs[0]);

    if (!initialized) {
        if (nlhs != 0)
            mexErrMsgIdAndTxt("mex:error", "Wrong number of arguments.");
        unsigned int seed = static_cast<unsigned int>(in);
        srand(seed);
        initialized = true;
    }
    else {
        mwSize len = static_cast<mwSize>(in);
        plhs[0] = mxCreateDoubleMatrix(len, 1, mxREAL);
        double *x = mxGetPr(plhs[0]);
        for (mwSize i=0; i<len; ++i)
            x[i] = rand()%256;
    }
}

现在在MATLAB中:

>> mex -largeArrayDims -silent myrand.cpp
>> myrand(1234)    % seed
>> myrand(5)       % generate 5x1 vector
ans =
   228
   213
   217
    54
    16
>> myrand(3)
ans =
    37
   170
   188
>> clear myrand    % unload MEX-file from memory
>> myrand(1234)    % seed with the same number
>> myrand(5)       % generates same sequence as before
ans =
   228
   213
   217
    54
    16

如果需要,还可以通过在播种后使用mexLock防止MEX功能被卸载。 但是,您必须公开一种特殊的语法,该语法最终会调用相应的mexUnlock (类似myrand(-1)或任何负数的大小)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM