Clear Filters
Clear Filters

Seeding RNG in MEX function

3 views (last 30 days)
Amit on 19 Jul 2014
Answered: Shyam Sangaraju on 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 */
plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
Y = mxGetPr(plhs[0]);
*Y = ((double) (rand()))/((double)(RAND_MAX));
Thank you for your time.

Answers (1)

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


Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!