Seeding RNG in MEX function

조회 수: 5 (최근 30일)
Amit
Amit 2014년 7월 19일
답변: Shyam Sangaraju 2014년 7월 22일
Hi guys,
I recently started to learn MEX to improve the speed on some of my code. As I deal with a lot of Monte Carlo simulations, random numbers become important. I have two questions: #1 Is there any available function in the mex library that I can use instead of native C++ rand function #2 Every time I try to seed the random number generator, I get the same random number. Without seeding, the numbers seem random though. (I am planning to move away from C++ native random function and use better ones, once I figure this out).
My attempt is posted below -
#include <time.h>
#include <math.h>
#include "mex.h"
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
double *Y;
int ii;
/* rand seed */
//srand((unsigned)time(NULL));
plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
Y = mxGetPr(plhs[0]);
*Y = ((double) (rand()))/((double)(RAND_MAX));
return;
}
Thank you for your time.

답변 (1개)

Shyam Sangaraju
Shyam Sangaraju 2014년 7월 22일
MEX library does not have a specific function to generate random numbers. In the code you have provided, you are trying to seed the random number generator using the function “srand((unsigned)time(NULL))”. This function sets the seed based on the current time. As long as you don't start two instances of the code within a second of each other, you should safely expect a different random number.

카테고리

Help CenterFile Exchange에서 MATLAB Compiler에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by