Seeding RNG in MEX function
4 views (last 30 days)
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 -
void mexFunction( int nlhs, mxArray *plhs,
int nrhs, const mxArray *prhs)
/* rand seed */
plhs = mxCreateDoubleMatrix(1, 1, mxREAL);
Y = mxGetPr(plhs);
*Y = ((double) (rand()))/((double)(RAND_MAX));
Thank you for your time.
Shyam Sangaraju on 22 Jul 2014
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.