| SimEvents® | ![]() |
| On this page… |
|---|
Basic Procedure for Running Simulations Repeatedly Example: Running a Simulation Repeatedly to Compute an Ensemble Average |
Running simulations repeatedly can be important for gathering valid statistics. You typically use the MATLAB® Command Window or an M-file to run simulations repeatedly. A typical procedure is as follows:
Configure your model to record relevant data in the MATLAB workspace for subsequent analysis or file storage. The Discrete Event Signal to Workspace block is particularly useful for this.
(Optional): Remove plotting blocks whose operation may reduce the simulation speed. When running simulations unattended, you are not viewing plots anyway.
Write M-code that runs the simulation and analyzes the results. Typical constructs can include:
for loop for repeating simulation runs.
set_param commands if you need to vary some aspects of the model between simulation runs.
se_randomizeseeds and se_getseeds commands if you need to change random number sequences between simulation runs and store the seeds for future reference.
sim command to run the simulation programmatically. To learn more about sim, see Running a Simulation Programmatically in the Simulink® documentation.
save or array-building commands that store results from each simulation run if the next simulation run would overwrite them.
Suppose you want to run the Single Server Versus N-Server demo model multiple times to compute ensemble averages for the waiting times. You can do this by configuring the model to make it suitable for statistical analysis, simulating the modified model multiple times, and then analyzing the results. Here are the specific steps:
Open the model by entering sedemo_single_v_multi_server in the MATLAB Command Window.
Save the model as server_stats.mdl in either the current directory or a writable directory on the MATLAB path.
From the SimEvents Sinks library, drag the Discrete Event Signal to Workspace block into the model and set these parameters in the block dialog box:
Set Limit data points to last to 1 because only the final value of the statistic is relevant for this example.
Set Save format to Array.
Replace the block labeled Average Wait, in the top portion of the model, with the Discrete Event Signal to Workspace block.
Drag a second copy of the Discrete Event Signal to Workspace block into the model and set these parameters in the block dialog box:
Set Variable name to simoutN.
Set Limit data points to last to 1.
Set Save format to Array.
Replace the block labeled Average Wait1, in the bottom portion of the model, with the second Discrete Event Signal to Workspace block.
Resave the model, which is now suitable for statistical analysis of the waiting time.
To run the simulation repeatedly and capture the statistic from each run, execute the following code in the MATLAB environment.
% Set up.
nruns = 10; % Number of simulation runs
w1 = zeros(nruns,1); % Preallocate space for array to build for results.
wN = zeros(nruns,1);
h = waitbar(0,'Running simulations. Please wait...');
% Main simulation loop
for k = 1:nruns
waitbar(k/nruns,h); % Update progress indicator.
se_randomizeseeds('server_stats'); % Change random number sequence.
sim('server_stats',[]); % Run simulation.
w1(k) = simout; % Build array of empirical values for single server.
wN(k) = simoutN; % Build array of empirical values for N-server.
end
close(h); % Close progress indicator window.To display some information about the collected statistics, enter the following code in the MATLAB Command Window.
disp('Ensemble average for single server is:');
disp(mean(w1));
disp('Ensemble average for N-server is:');
disp(mean(wN));Sample output is below. Your results might vary because the initial seed for the random number generator is not deterministic.
Ensemble average for single server is:
1.9898
Ensemble average for N-server is:
3.4567Suppose you want to run the Single Server Versus N-Server demo model with different values of N. You can do this by configuring the model to make it suitable for statistical analysis with a varying parameter, simulating the modified model multiple times with different values of the parameter, and then analyzing the results. Here are the specific steps:
Open the model by entering sedemo_single_v_multi_server in the MATLAB Command Window.
Save the model as server_vary_n.mdl in either the current directory or a writable directory on the MATLAB path.
Remove the entire portion of the model labeled "Single Server with Service Time = 1". The portion of the model labeled "N-Server with N=3, Each with Service Time = 3" remains.
From the SimEvents Sinks library, drag the Discrete Event Signal to Workspace block into the model.
In the Discrete Event Signal to Workspace block's dialog box:
Set Limit data points to last to 1 because only the final value of the statistic is relevant for this example.
Set Save format to Array.
Replace the block labeled Average Wait1 with the Discrete Event Signal to Workspace block. The model looks like the following figure.

Open the dialog box of the block labeled Average Service Time = 3 and set Mean to N, which is a MATLAB variable to be defined later.
Open the dialog box of the block labeled 3 Servers and set Number of servers to N.
Resave the model, which is now suitable for statistical analysis of the waiting time with varying values of N.
To run the simulation repeatedly while varying the value of N, and capture the statistic from each run, execute the following code in the MATLAB environment. Note that it takes some time to run.
% Set up.
nruns = 20; % Number of simulation runs
Nvec = (1:5); % Values of N
nN = length(Nvec); % Number of values in Nvec
% Preallocate space for results.
w = zeros(nruns,1);
wavg = zeros(nN,1);
% Vary the mean arrival rate.
for Nidx = 1:nN
% N is a parameter in two blocks, so changing N changes the number of
% servers and the mean service rate in the simulation.
N = Nvec(Nidx);
disp(['Simulating with number of servers = ' num2str(N)]);
% Compute ensemble average for each value of N.
for k = 1:nruns
se_randomizeseeds('server_vary_n'); % Change random number sequence.
sim('server_vary_n',1000); % Run simulation.
w(k) = simout; % Store empirical value of w.
end
wavg(Nidx) = mean(w); % Average for fixed value of N
endTo plot the average waiting time (averaged over multiple simulations for each fixed value of N) against N, execute the following code in the MATLAB environment.
figure; % Create new figure window.
plot(Nvec,wavg,'r*'); % Plot empirical values.
xlabel('Number of Servers')
ylabel('Average Waiting Time (s)')
axis([0 max(Nvec)+1 0 max(wavg)*1.1]);A sample plot is below.

![]() | Varying Simulation Results by Managing Seeds | Regulating the Simulation Length | ![]() |
| © 1984-2008- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |