Simulink random number repeats every time the simulation runs

5 次查看(过去 30 天)
Hi,
In Simulink, using RTW, I need to generate a random number in the [1,3] range and i need the number to be different every simulation. Is there any comand to generate a random seed and not get the same seed every simulation that does not involve using extrinsic functions?
Thanks in advance!

回答(2 个)

Jan
Jan 2011-5-30
Seed the random number generator in the InitFcn:
RandStream.setDefaultStream( ...
RandStream('mt19937ar', 'seed', sum(100 * clock))
Actually it should be enough to do this once in a Matlab session. Therefore I assume a PERSISTENT variable might be helpful:
persistent Seeded
if isempty(Seeded)
... the above seeding code
Seeded = true;
end

Paulo Silva
Paulo Silva 2011-5-30
Go to File, Model Properties, callbacks, InitFcn
n=randi([1 3])
if you don't wan't to have repeated n values, first check if n exists in the workspace, if it exist get it's value and generate n values until they are diferent (while (n0==n) generate another n)
if ismember('n',who) %check if there's already one n value in memory
n0=n; %there's one, save it to n0
while (n0==n) %get another n diferent from n0
n=randi([1 3]);
end
else
n=randi([1 3]); %there's no n in memory get one
end
The code can fail if there's one n in memory that's not a number, use a variable with a big and/or unique name or add code to handle that situation.

类别

Help CenterFile Exchange 中查找有关 Sources 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by