フィルターのクリア

Generate the same result using random number generator

14 ビュー (過去 30 日間)
Ezgi
Ezgi 2020 年 7 月 21 日
回答済み: Steven Lord 2020 年 7 月 21 日
I have code that uses the random number generator at the beginning of the file. The 'rng(x)' function is in a for loop where 'x' is the different seeds that I use to generate different numbers. Let's say that 'x' is from 1 to 10. Every time I run the code, it is supposed to generate the same random numbers,apply some operations on the numbers and generate the same results. However, each time I run the code I get different results. What could be the problem?
for x=1:10
rng(x)
d=rand(5,1);
some operations where rand is used at other places as well
end
Thank you.
  1 件のコメント
Cris LaPierre
Cris LaPierre 2020 年 7 月 21 日
I get the same random numbers using your code.

サインインしてコメントする。

回答 (1 件)

Steven Lord
Steven Lord 2020 年 7 月 21 日
If you think calling rng inside the loop somehow makes the numbers "more random", it doesn't as stated in the Note on this documentation page.
If you want to initialize the random number generator, calling rng once before you enter the loop is probably sufficient.
rng(42) % arbitrary choice
d = zeros(5, 10);
for x = 1:10
d(:, x) = rand(5, 1);
end
rng(42) % same arbitrary choice
f = zeros(5, 10);
for x = 1:10
f(:, x) = rand(5, 1);
end
rng(43) % different arbitrary choice
g = zeros(5, 10);
for x = 1:10
g(:, x) = rand(5, 1);
end
Note that each column of d contains different numbers, the elements of f are the same as the elements of d, and the elements of g are different from those of d and f.
You might find the topics in the Control Random Number Generation section on this documentation page useful.

カテゴリ

Help Center および File ExchangeRandom Number Generation についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by