MATLAB: Run rng Function Before Each Simulation Run

parsimpresimfcnrngsimulink

Hi,
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:
numofSims=4;
simIn(1:numofSims)=Simulink.SimulationInput(model);
for i=1:numofSims
simIn(i).PreSimFcn=@(x) rng(i);
end
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:
Simulink.SimulationInput
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,
Baris

Best Answer

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
numofSims=4;
simIn(1:numofSims)=Simulink.SimulationInput(model);
for i=1:numofSims
simIn(i).PreSimFcn=@(x) seedRNG(i);
end
simOut=parsim(simIn, 'TransferBaseWorkspaceVariables', true, 'showProgress', true);
function seedRNG(seedValue)
rng(seedValue)
end