Generate the same result using random number generator

20 visualizaciones (últimos 30 días)
Ezgi
Ezgi el 21 de Jul. de 2020
Respondida: Steven Lord el 21 de Jul. de 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.

Respuestas (1)

Steven Lord
Steven Lord el 21 de Jul. de 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.

Categorías

Más información sobre Random Number Generation en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by