pseudo-random number generator rand() in .mex
이전 댓글 표시
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.
댓글 수: 2
Elliott Rachlin
2018년 10월 12일
I notice that in a mex file, the code "rand()" seems to return an integer between 0 and 32767, not the value between 0.0 and 1.0 that I was expecting. Does anybody know why this is (and why the documentation does not seem to mention this)?
Walter Roberson
2018년 10월 12일
That is, you are invoking C's rand(), not invoking MATLAB's rand()
채택된 답변
추가 답변 (1개)
James
2011년 5월 3일
댓글 수: 1
James Tursa
2011년 5월 3일
Yes and no. Using srand (or rand) in one mex routine will affect other mex routines that use rand. However, there is apparently another piece of the library hanging around in memory even after you clear the mex routines, so at least in my testing you will not get a fresh start this way by just doing clear. You must use srand.
카테고리
도움말 센터 및 File Exchange에서 Write C Functions Callable from MATLAB (MEX Files)에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!