簡體   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