Matlab rng 命令的使用

rng Control the random number generator used by RAND, RANDI, and RANDN. 
rng(SD) seeds the random number generator using the non-negative integer SD so that RAND, RANDI, and RANDN produce a predictable sequence of numbers. 
如:

% Get generator settings.
s = rng;

% Call rand.
x = rand(2,3);

% Restore previous generator 
% settings.
rng(s);

% Call rand again and 
% get the same results.
y = rand(2,3)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

得到的x与y是完全相同的(因为y与x是在同一个 random number generator里);再如:

% Get generator settings.
s = rng;

% Call rand.
x = rand(2,4)

% Restore previous generator 
% settings.
rng(s);

% Call rand again and 
% get the same results.
y = rand(3,2)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

得到的结果为

x =

    0.2760    0.6551    0.1190    0.9597
    0.6797    0.1626    0.4984    0.3404


y =

    0.2760    0.1626
    0.6797    0.1190
    0.6551    0.4984
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

对比可见,y是在x里面按列取值的。而

x = rand(2,3);
y = rand(2,3)
  • 1
  • 2

得到的x与y则是完全随机,即不相同的。 
更具体可参见help文件。

% 每次打开matlab之后生成相同的随机数,在rand一类的命令前加上以下两行命令
rng('default') % 每次打开matlab之后初始化到相同
rng(1) % 选择 seed

猜你喜欢

转载自blog.csdn.net/kebu12345678/article/details/80938394