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.)
rng( seed ) specifies the seed for the MATLAB® random number generator. For example, rng(1) initializes the Mersenne Twister generator using a seed of 1 . The rng function controls the global stream, which determines how the rand , randi , randn , and randperm functions produce a sequence of random numbers.
One simple way to avoid repeating the same random numbers in a new MATLAB session is to choose a different seed for the random number generator. rng gives you an easy way to do that, by creating a seed based on the current time. Each time you use 'shuffle' , it reseeds the generator with a different seed.
Syntax: set.seed(123) In the above line,123 is set as the random number value. The main point of using the seed is to be able to reproduce a particular sequence of 'random' numbers. and sed(n) reproduces random numbers results by seed. For more information for set.
In R, we can set a random seed to make the output of our R code reproducible. By setting a specific seed, the random processes in our script always start at the same point and hence lead to the same result.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With