the C random seed is not shared by two mex-complied files
7 views (last 30 days)
Show older comments
Hi I have two .cpp files with the identical code. Both of them call rand() from standard C library. After complie the .cpp with mex, the two codes return the same random data both for the first calling. It means they don't share the random seed. I want them to share the random seed. The appendix is the code used for test. Thanks.
Best wish
randtest1.cpp/randtest2.cpp
using namespace std;
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { double *pData;
plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
pData = mxGetPr(plhs[0]);
pData[0] = rand();
}
0 Comments
Answers (2)
Sachin Ganjare
on 18 Oct 2012
I think srand function should be used before rand function, to avoid this.
Refer link below for further details:
Hope it helps!!
Kaustubha Govind
on 18 Oct 2012
MEX-files are the equivalent of shared libraries (DLLs on Windows) - I don't know too much about how rand() operates, but it seems plausible that two different MEX-files don't share the same seed - you can perhaps verify this behavior by creating two DLLs (outside of MATLAB) and see if they share the seed.
Perhaps it is best that you use some kind of static variable as a flag to initialize the seed once when each MEX-file is first run. You could use a technique like in the example on this page to initialize the seed depending on the current time, instead of a constant initial value.
0 Comments
See Also
Categories
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!