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에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!