Filter löschen
Filter löschen

Generate the same result using random number generator

14 Ansichten (letzte 30 Tage)
Ezgi
Ezgi am 21 Jul. 2020
Beantwortet: Steven Lord am 21 Jul. 2020
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.

Antworten (1)

Steven Lord
Steven Lord am 21 Jul. 2020
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.

Kategorien

Mehr zu Random Number Generation finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by