MATLAB Answers

YT
0

rng(s) takes previous seed instead of current one

YT
さんによって質問されました 2018 年 12 月 10 日
最新アクティビティ YT
さんによって コメントされました 2018 年 12 月 10 日
I've encountered this problem when using functions in combination with user input and rng(s). To clarify my problem, I've got the following 2 scripts:
%main.m
user_seed = "1739995225";
disp(['Main input seed = ' char(user_seed)]);
checkSeed(user_seed)
and
%checkSeed.m
function checkSeed(user_seed)
%clear s seeder;
seeder = double(user_seed);
%check if seed isset
if exist('seeder','var') == 1
s = rng(seeder);
disp(['Function seed = ' num2str(s.Seed)]);
else
s = rng('shuffle');
disp(['random seed = ' num2str(s.Seed)]);
end
end
The issue is that everytime the previous user seed is being used instead of the current one. For example
%first run
user_seed = "1739995225";
%Main input seed = 1739995225
%Function seed = 1739995225
%second run
user_seed = "1739995226";
%Main input seed = 1739995226
%Function seed = 1739995225
%third run
user_seed = "1739995227";
%Main input seed = 1739995227
%Function seed = 1739995226
I tried putting the checkSeed.m contents in the main script, but that gave me the same result. Also tried adding clear s seeder; to the function but that didnt help either. So any ideas?

  0 件のコメント

サインイン to comment.

製品


リリース

R2018b

2 件の回答

Walter Roberson
回答者: Walter Roberson
2018 年 12 月 10 日
 採用された回答

This is not a bug. This is how rng is defined. The documentation says:
"sprev = rng(...) returns the previous settings of the random number generator used by rand, randi, and randn before changing the settings."
The reason for this is that it permits you to code
prev = rng(new)
...
rng(prev)
instead of having to code
prev = rng
rng(new)
...
rng(prev)

  1 件のコメント

YT
2018 年 12 月 10 日
Ah didn't read the documentation good enough then. Thanks.
I fixed it by doing the following instead (for future readers)
if exist('seeder','var') == 1
rng(seeder);
else
rng('shuffle');
end
s = rng;
disp(['Seed = ' num2str(s.Seed)]);

サインイン to comment.


Steven Lord
回答者: Steven Lord
2018 年 12 月 10 日

This is the expected and documented behavior of rng. From the documentation: "sprev = rng(...) returns the previous settings of the random number generator used by rand, randi, and randn before changing the settings."
This allows you to "remember" the previous state of the generator and change it to a different state in one call then (when you're done generating random numbers) restore the remembered state with a second rng call.
What exactly are you trying to do with that code? If you describe in words what you want to happen, we may be able to help you make that happen.

  0 件のコメント

サインイン to comment.



Translated by