How do I use a different random number seed in a for each subsystem?
조회 수: 2(최근 30일)
I'm trying to run a variety of random number calls inside of a for-each subsystem. As a simple example, consider this system:
And inside the for each:
In that random number generator I do:
So, the problem is that the "for each" subsystem uses the same random number seeds for each iteration. There are some work-arounds, but they will require large code changes to the "real" code I'm trying to put in a "for-each" subsystem. For example, the "for-each" system can be masked with a seed parameter vector, which can be partitioned and used in the Seed input to the random number. But this requires each seed to be explicitly defined. I was just curious if anyone else had a better solution.
Salman Ahmed 2021년 11월 16일
From my understanding, you wish to generate a random number with a different seed for each different iteration. I think this could be achieved using a MATLAB function block that replaces your random generator block as shown below.
The logic of the MATLAB function block can be written as:
function y = fcn(seed)
switch seed % Define random number seeds for each iteration
y = randi(1e6);
y = randi(2e6);
y = randi(3e6);
y = randi(4e6);
y = randi(5e6);
y = randi(6e6);
This behaviour is caused because the function blocks are compiled into MEX files rather than being evaluated line by line as in MATLAB. The seed for the random number generator remains the same across each simulation since it is the same in the MEX file.
Note that the line "coder.extrinsic('randi')" be included at the top of your MATLAB Function Block script as shown. This will declare the random number generator function as extrinsic, and therefore generate a call to MATLAB's "randi" function, rather than including the code for this function inside the MEX file.