the C random seed is not shared by two mex-complied files
Mostrar comentarios más antiguos
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();
}
Respuestas (2)
Sachin Ganjare
el 18 de Oct. de 2012
0 votos
I think srand function should be used before rand function, to avoid this.
Refer link below for further details:
Hope it helps!!
Kaustubha Govind
el 18 de Oct. de 2012
0 votos
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.
Categorías
Más información sobre Write C Functions Callable from MATLAB (MEX Files) en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!