Run rng Function Before Each Simulation Run

4 views (last 30 days)
I would like to run a set of Simulink simulations by parsim function with different random number generator setting in each consecutive run. I tried the way below but it does not work:
for i=1:numofSims
simIn(i).PreSimFcn=@(x) rng(i);
simOut=parsim(simIn, 'TransferBaseWorkspaceVariables', true, 'showProgress', true);
It gives the error:
'Error executing ''PreSimFcn'' on SimulationInput object. Caused by: Expected input to be one of these types:
Instead its type was struct.'
How can I achieve it? In Simulink model I have an Embedded MATLAB Function block and in that block I call rand function to generate predictable (due to pre-run rng function) random number.
Thanks in advance,
  1 Comment
Elliott Rachlin
Elliott Rachlin on 23 Oct 2018
Similar question: I am creating a SimEvents model programmatically and repeatedly running it multiple times from a script that executes the following sequence: rng(x);sim(xxx) where x is the number of the simulation being run (and xxx is all the parameters that sim requires). I find that all simulations give the same result, apparently ignoring the rng(x) command given just prior to each simulation made with sim(xxx). Does sim(xxx) ignore the current seed and reinitialize the random number generator? If so, how can I set a seed in a SimEvents model (which is initiated by sim(xxx))?

Sign in to comment.

Accepted Answer

Rahul Kumar
Rahul Kumar on 29 Aug 2018
The PreSimFcn expects a SimulationInput object to be returned (in case any output is returned) and in this case 'rng' returns a struct causing the PreSimFcn to error out. You can achieve what you are looking for by defining a local function which does not return any output
for i=1:numofSims
simIn(i).PreSimFcn=@(x) seedRNG(i);
simOut=parsim(simIn, 'TransferBaseWorkspaceVariables', true, 'showProgress', true);
function seedRNG(seedValue)

More Answers (0)





Community Treasure Hunt

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

Start Hunting!