Generate the same result using random number generator

조회 수: 18 (최근 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개)

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 CenterFile Exchange에서 Random Number Generation에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by