the C random seed is not shared by two mex-complied files

7 views (last 30 days)
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
#include cstdlib #include mex.h
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();
}

Answers (2)

Sachin Ganjare
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!!
  2 Comments
Zhijian Yu
Zhijian Yu on 18 Oct 2012
When srand is not used, the random seed is set to 1. If the two mex file to have one random seed, the different data are return for the first call of randtest1 and randtest2.
Here I show the problem
K>> randtest1 -- This is the first time to call randtest1
ans =
41
K>> randtest2 -- This is the first time to call randtest1
ans =
41 -- I want this value to be different from 41
K>> randtest1
ans =
18467
K>> randtest2
ans =
18467

Sign in to comment.


Kaustubha Govind
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.

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!