How to freeze a random sample
古いコメントを表示
I need to generate a random sample between (0,1) and freeze it so that when I run the program again it generates the same "random" sample. Matlab help gave me:
% Save v5 generator state.
st = rand('state');
% Call rand.
x = rand(1,4);
% Restore v5 generator state.
rand('state',st);
% Call rand again and hope
% for the same results.
y = rand(1,4)
First iteration output is: x =
0.59494 0.27395 0.0481 0.83809
y =
0.59494 0.27395 0.0481 0.83809
But second run produces different sequence: x =
0.10254 0.72827 0.4405 0.99719
y =
0.10254 0.72827 0.4405 0.99719
I need it to give me the same results, so the second run should be: x =
0.59494 0.27395 0.0481 0.83809
y =
0.59494 0.27395 0.0481 0.83809
I know this involves using a seed but the help wasn't clear to me. The rng function doesn't work in my version.
採用された回答
その他の回答 (3 件)
Walter Roberson
2011 年 11 月 29 日
As an experiment, after your line
st = rand('state');
Try adding
rand('state',st);
That would "restore" the state you just saved. Although that should be the same as what you already do, there is a possibility that some of the complete state information does not get saved, in which case forcing the state to be the same both times should make a difference.
No promises on this, but it is worth a try.
Honglei Chen
2011 年 11 月 29 日
There are some side effects using the syntax Walter mentioned. Basically MATLAB changes the random number generator silently behind the scene.
If you are using a version after R2011a, you should take a look at
doc rng
If you are using a version after R2008b but before R2011a, then you can take a look at
doc Randstream
The two functions the same, but the interface of rng is simpler.
HTH
Fangjun Jiang
2011 年 11 月 29 日
What about 'seed'? I always use 'seed' as a way to uniquely identify a series of random data. As long as you specify the same seed, you can get the same series of random data.
>> rand('seed',1);rand(1,5)
ans =
0.5129 0.4605 0.3504 0.0950 0.4337
>> rand('seed',1);rand(1,5)
ans =
0.5129 0.4605 0.3504 0.0950 0.4337
>> rand('seed',1);rand(1,5)
ans =
0.5129 0.4605 0.3504 0.0950 0.4337
>> rand('seed',1);rand(1,5)
ans =
0.5129 0.4605 0.3504 0.0950 0.4337
>> rand('seed',1);rand(1,5)
ans =
0.5129 0.4605 0.3504 0.0950 0.4337
1 件のコメント
Honglei Chen
2011 年 11 月 29 日
It has the same effect as 'state'. When y ou call rand('seed',1), it actually switch to a specific random number generator.
カテゴリ
ヘルプ センター および File Exchange で Random Number Generation についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!