the C random seed is not shared by two mex-complied files
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (2)
Sachin Ganjare
am 18 Okt. 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
am 18 Okt. 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 Kommentare
Siehe auch
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!