How do I use a different random number seed in a for each subsystem?
10 views (last 30 days)
Show older comments
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.
0 Comments
Answers (1)
Salman Ahmed
on 16 Nov 2021
Hi James,
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)
y=0;
coder.extrinsic('randi');
switch seed % Define random number seeds for each iteration
case 1
y = randi(1e6);
case 2
y = randi(2e6);
case 3
y = randi(3e6);
case 4
y = randi(4e6);
case 5
y = randi(5e6);
otherwise
y = randi(6e6);
end
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.
See Also
Categories
Find more on Sources in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!