MATLAB Random Seed

July 7, 2015

A shocking thing about random seed in MATLAB is that the random seed is initialized by the same value every time we start MATLAB.

The story is as follows.


We were trying to run numerical results on Sherlock for our new paper “Multidimensional Butterfly Factorization” which is collaborating with Haizhao Yang and Lexing Ying. As been pointed out in previous papers [1,2], an evaluation of true relative error is too expansive to compute. Hence, the relative error was evaluated in a subsampled set of points, i.e.,

\[\epsilon = \sqrt{\frac{\sum_{x\in S}\lvert u^d(x)-u^a(x) \rvert^2} {\sum\_{x\in S}\lvert u^d(x) \rvert^2}}\]

where $u^d$ is the result of direct evaluation, $u^a$ is the result of the fast algorithm, and $S$ is a point set of size 256.

On Sherlock, all jobs have to be submitted via sbatch files. In each sbatch file, we will start MATLAB and run the script. However, we found that the evaluated relative error is constant over several runs. At the beginning, we thought there was a bug in the code, especially, in the relative error evaluation part. After a careful debugging and double checking the relative error, we finally came to this finding.


We start a new MATLAB, and the following lines are always true on my Mac Pro.

>> rand()

ans =

    0.8147

>> randn()

ans =

    1.8339

A nice way to have true random values every run, we could suggest to initialize the random seed with current computer time. And as been pointed out in the help file of rng, we could put the following line at the beginning of the code:

rng('shuffle');

such that it seeds the random number generator based on the current time.

 

Yingzhou Li

Discussion

I'm a faculty at Fudan University. Follow me on Github and Bitbucket. Hopefully, you will find my code useful. You are also welcome to either email me or post comments below to discuss on these posts.