## Event Action Languages and Random Number Generation

You can write SimEvents^{®} actions using:

MATLAB

^{®}code — Use MATLAB. For information on guidelines for using MATLAB code as the event action language, see Guidelines for Using MATLAB as the Event Action LanguageSimulink

^{®}functions — Use the Simulink Function block. The Simulink Function block does not accept entities as input.

### Guidelines for Using MATLAB as the Event Action Language

In general, using MATLAB as the SimEvents event action language follows the same rules as the use of MATLAB in the MATLAB Function block.

Include a type prefix for identifiers of enumerated values — The identifier

`TrafficColors.Red`

is valid, but`Red`

is not.Use the MATLAB format for comments — Use

`%`

to specify comments for consistency with MATLAB. For example, the following comment is valid:`% This is a valid comment in the style of MATLAB`

Use one-based indexing for vectors and matrices — One-based indexing is consistent with MATLAB syntax.

Use parentheses instead of brackets to index into vectors and matrices — This statement is valid:

a(2,5) = 0;

This statement is not valid:

a[2][5] = 0;

Persistent variable guidelines:

Manage states that are not part of the entity structure using MATLAB persistent variables.

Persistent variables defined in any event action of a block are scoped to only that action.

Block can share persistent variables across all of its event action by managing it in a MATLAB function on path (that is invoked from its event actions).

Two different blocks cannot share the same persistent variable.

Assign an initial value to local and output data — When using MATLAB as the action language, data read without an initial value causes an error.

Do not use parameters that are of data type cell array.

### Generate Random Numbers with Event Actions

You can generate random numbers using various distributions. There are two modeling approaches to use seeds during random number generation.

You can use persistent variables for initializing unique seeds for each block in your model.

You can use

`coder.extrinsic()`

function to generate seeds without persistent variables.

To generate these random distributions, use code in the **Usage**
column of this table in SimEvents blocks that support event actions or intergeneration time actions.

Distribution | Parameters | Usage | Requires Statistics and Machine Learning Toolbox™ Product |
---|---|---|---|

Exponential | Mean (m) |
-m * log(1-rand) | No |

Uniform | Minimum (m) Maximum (M) |
m + (M-m) * rand | No |

Bernoulli | Probability for output to be 1 (P) |
binornd(1,P) | Yes |

Binomial | Probability of success in a single trial (P) Number of trials (N) |
binornd(N,P) | Yes |

Triangular | Minimum (m) Maximum (M) Mode (mode) |
persistent pd if isempty(pd) pd = makedist('Triangular',... 'a',m,'b',mode,'c',M) end random(pd) | Yes |

Gamma | Threshold (T) Scale (a) Shape (b) |
gamrnd(b,a) | Yes |

Gaussian (normal) | Mean (m) Standard deviation (d) |
m + d*randn | No |

Geometric | Probability of success in a single trial (P) |
geornd(P) | Yes |

Poisson | Mean (m) |
poissrnd(m) | Yes |

Lognormal | Threshold (T) Mu (mu) Sigma (S) |
T + lognrnd(mu,S) | Yes |

Log-logistic | Threshold (T) Scale (a) |
persistent pd if isempty(pd) pd = makedist('Loglogistic',... 'mu',m,'sigma',S); end random(pd) | Yes |

Beta | Minimum (m) Maximum (M) Shape parameter a (a) Shape parameter b (b) |
betarnd(a,b) | Yes |

Discrete uniform | Minimum (m) Maximum (M) Number of values (N) |
persistent V P if isempty(V) step = (M-m)/N; V = m : step : M; P = 0 : 1/N : N; end r = rand; idx = find(r < P, 1); V(idx) | No |

Weibull | Threshold (T) Scale (a) Shape (b) |
T + wblrnd(a,b) | Yes |

Arbitrary continuous | Value vector (V) Cumulative probability function vector (P) |
r = rand; if r == 0 val = V(1); else idx = find(r < P,1); val = V(idx-1) + ... (V(idx)-V(idx-1))*(r-P(idx-1)); end | No |

Arbitrary discrete | Value vector (V) Probability vector (P) |
r = rand; idx = find(r < cumsum(P),1); V(idx) | No |

For an example, see Model Traffic Intersections as a Queuing Network.

If you need additional random number distributions, see Statistics and Machine Learning Toolbox.

#### Random Number Distribution with Persistent Variables

To generate random numbers, initialize a unique seed for each block in your model. If you use a statistical pattern, you can manually change the initial seed to a unique value for each block to generate independent samples from the distributions.

To reset the initial seed value each time a simulation starts, use MATLAB code to initialize a persistent variable in event actions, for example:

persistent init if isempty(init) rng(12234); init=true; end

Here is an example code. The value vector is assigned to
`FinalStop`

:

% Set the initial seed. persistent init if isempty(init) rng(12234); init=true; end % Create random variable, x. x=rand(); % % Assign values within the appropriate range % using the cumulative probability vector. if x < 0.3 entity.FinalStop = 2; elseif x >= 0.3 && x< 0.6 entity.FinalStop = 3; elseif x >= 0.6 && x< 0.7 entity.FinalStop = 4; elseif x >= 0.7 && x< 0.9 entity.FinalStop = 5; else entity.FinalStop = 6; end

#### Random Number Generation with Callbacks

In some scenarios, you generate random numbers without using the persistent
variables. In this case, use `coder.extrinsic()`

function to make
sure that SimEvents is using the function in MATLAB and a seed is defined in the base workspace of MATLAB. This may cause performance decrease in simulation.

Consider this code as an example.

% Random number generation coder.extrinsic('rand'); value = 1; value = rand(); % Pattern: Exponential distribution mu = 0.5; dt = -1/mu * log(1 - value);

The output of the extrinsic function is an `mxArray`

. To convert
it to a known type, a variable `val = 1`

is declared to set its type
to double and `rand`

is assigned to that variable
`val=rand`

. For information about extrinsic functions, see Working with mxArrays.

For an example, see Model Traffic Intersections as a Queuing Network.

### Parameters in Event Actions

From within an event action, you can refer to these parameters:

Mask-specific parameters you define using the Mask Editor

**Parameters**pane.Any variable you define in a workspace (such as base workspace or model workspace).

Parameters you define using the

`Simulink.Parameter`

object.

## Limitations of Event Actions

You cannot modify parameters from within an event action.

You cannot tune parameters used in event actions during a simulation.

You cannot use string or character vector data types for entity attribute values.

You cannot use structures passed from block mask parameters that contain character vectors or strings.

You cannot use breakpoints in a MATLAB function that is called from an event action.

## See Also

Simulink Function | Entity Generator | Entity Queue | Multicast Receive Queue | Entity Server | Entity Terminator | Entity Replicator | Resource Acquirer | MATLAB Function | `Simulink.Parameter`