MATLAB: Pseudo-random number generator rand() in .mex

randrandomrandom number generator

In standard C, the following code generate 5 random numbers.
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
/* Now generate 5 pseudo-random numbers */
int i;
for (i=0; i<5; i++)
{
printf ("rand[%d]= %u\n",
i, rand ());
}
return 0;
}
Each time you run the program, same serial of 5 numbers will be generated since the seed is retested. However, the same code as a mex function does not behave like this. Here is the mex code:
#include <stdio.h>
#include <stdlib.h>
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[]) {
/* Now generate 5 pseudo-random numbers */
int i;
for (i=0; i<5; i++)
{
mexPrintf ("rand[%d]= %u\n",
i, rand ());
}
return;
}
Every time this mex function produces different serial of 5 random numbers. Does anybody know why? How the mex function resets the seed number each time? Thanks in advance.

Best Answer

When you first run a mex function it loads into memory and stays in memory until it gets cleared. So any variables that are global or persistent in the mex function, like a random number generator seed that the rng internally maintains, will retain the last value between calls. So you get a new set of numbers with each call. If you want to start fresh each time you can either clear the mex function from memory or in the mex code itself reinitialized the rng each time you enter the mex function.
Related Question