Simulink random number repeats every time the simulation runs

조회 수: 5 (최근 30일)
Max
Max 2011년 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