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.
Seeding RNG in MEX function
5 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
回答(1 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!