Matlab creates same input values every time? Why?
显示 更早的评论
Hi everybody,
I'm creating processing times as follows:
function [ processing_times ] = PT( number_of_activity )
number_of_activity = 12;
min= 100;
max = 2500;
processing_times = randi([min max],1,number_of_activity)';
end
When I run this code, I obtain 12x1 matrix as follows:
1481
1372
760
696
1184
646
2031
2467
172
1386
309
2025
After that, I quit the Matlab and open it again.
I run the same code and I obtain the same 12x1 matrix. This is possible? I use
randi([min max],1,number_of_activity)'
code. This code includes randomness. How can I obtain the exactly same value when every time I close and reopen the Matlab. Shouldn't the Matlab give me different values every time I open and close it?
I use Matlab 2015a and I ran this code in 2023a but I encountered the same problem again.
采纳的回答
更多回答(3 个)
Karl Cronburg
2023-9-26
编辑:Karl Cronburg
2023-9-26
You can get a random seed based on the current operating system time with the rng function:
rng("shuffle");
See the doc page here: https://www.mathworks.com/help/matlab/ref/rng.html
Walter Roberson
2023-9-26
1 个投票
Every time you load matlab, it does the equivalent of rng('default') which initializes the seed to 0.
It is expected that the random number order is the same starting from the beginning of each MATLAB session.
Caution: although you can use rng('shuffle') to initialize the seed based on the current time, doing so is not considered secure. Do not use it for producing seeds for cryptographic communications, or for producing seeds for drawing lottery numbers. Creating good seeds for secure purposes is hard
Steven Lord
2023-9-26
1 个投票
Others have told you how to get the numbers to not repeat after startup. But to answer your "Why?" question, this is expected behavior. See this documentation page that explains why this happens.
类别
在 帮助中心 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!