How do I use a different random number seed in a for each subsystem?
11 次查看(过去 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.
0 个评论
回答(1 个)
Salman Ahmed
2021-11-16
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Sources 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!