Does Matlab uses the same seed generated by the main function for the functions that are called by that function? Results changed!!

6 次查看(过去 30 天)
I have a simulation code running (which is for 10 replications), and I am initializing a seed for each replication. Within the code I am calling some functions which are generating exponential random variables by exprnd function. For a fixed set of parameters my code runs properly (I ran it many times and got the exact same results as I want). Then to analyze something else, I updated the parameter set which should have no effect on total number of random numbers generated (since the time horizon is the same). However, updating the set changed the number of random numbers generated which is confusing. My question is does generating the seed in the main function and using it for other functions called work as I think? Is it possible that Matlab is using another generator for the called functions? Any suggestions/ideas is appreciated, thanks.

采纳的回答

valdal
valdal 2015-12-1
Yes, you can save the state of the random generator at any point.
In your case, you can save the generator just before calling your function, use another random generator during the function (different seed) and finally restore the first generator.

更多回答(1 个)

Thorsten
Thorsten 2015-12-1
编辑:Thorsten 2015-12-1
Matlab uses a single random number generator for RAND, RANDI, and RANDN, for the command line or in called function. Setting a seed and using the same sequence of calls to the random functions results in the same random numbers. You can get the current state of the random number generator using
sc = rng;
if sc is different after running the simulation with your different parameter sets, the number of calls has not been the same (if you set the rng to the same initial state before each simulation, of course). You could add some sc = rng; calls at crucial points of your code and compare the results to those values obtained from a previous run to narrow down the part where the simulation uses different number of calls to the random number generator for the different parameter sets.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by