30

I am generating data in R and Matlab for 2 separate analyses and I want to determine if the results in the two systems are equivalent. Between the 2 sets of code there is inherent variability due to the random number generator. If possible, I would like to remove this source of variability. Does anyone know of a way to set the same starting seed in both Matlab and R? I provide some demo code below.

%Matlab code
seed=rng %save seed
matlabtime1=randn(1,5) %generate 5 random numbers from standard normal 
rng(seed) %get saved seed
matlabtime2=randn(1,5) %generates same output as matlabtime1

#R code
set.seed(3) #save seed
r.time1=rnorm(5) #generate 5 random numbers from standard normal 
set.seed(3) #get saved seed
r.time2=rnorm(5) #generates same output as r.time1

Essentially, I want the results from matlabtime2 and r.time2 to match exactly. (The code I am using is more complex than this illustrative demo so rewriting in one language only is not really a feasible option.)

4
  • 1
    Since the various random number generators of the two languages might written completely differently, there's no way to set up the seeds so all of them match. Are you generating only normals? Commented May 31, 2012 at 4:30
  • 1
    Why not call R from within Matlab and thus derive all random numbers consistently? I imagine you could write a small R script in Matlab that would set.seed in R and return your vector of generated numbers into Matlab. If you are running UNIX, then this could be accomplished through a batch script type R job. The translation from one program will probably slow thing down, however. Commented May 31, 2012 at 9:34
  • David--yes I am only generating normals--in a multivariate VAR context.
    – Chris Z.
    Commented Jun 3, 2012 at 22:06
  • Marc in the box--I have started looking into calling R scripts from Matlab for other purposes but am still trying to get it to work properly. I see Ansari (below) posted a suggestion that will work in the meantime.
    – Chris Z.
    Commented Jun 3, 2012 at 22:08

1 Answer 1

32

I'm finding it difficult to get the same random numbers in R and MATLAB - even using the same seed for the same algorithm (Mersenne Twister).

I guess it's about how they are implemented - even with the same seed, they have different initial states (you can print and inspect the states both in R and MATLAB).

In the past when I've needed this, I generated random input, saved it as a file on disk, and fed it to both MATLAB and R.

Another option is to write C wrappers for a random number generator (there are many of these in C/C++) both for R and MATLAB and invoke those instead of the built-in ones.

1
  • 1
    Exactly what I would have recommended. Commented May 31, 2012 at 11:17

Not the answer you're looking for? Browse other questions tagged or ask your own question.