Seeding RNG in MEX function

3 Ansichten (letzte 30 Tage)
Amit
Amit am 19 Jul. 2014
Beantwortet: Shyam Sangaraju am 22 Jul. 2014
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.

Antworten (1)

Shyam Sangaraju
Shyam Sangaraju am 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.

Kategorien

Mehr zu Write C Functions Callable from MATLAB (MEX Files) finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by