Generate the same result using random number generator
18 次查看(过去 30 天)
显示 更早的评论
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
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Random Number Generation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!