Home Examples Random Numbers in Stateflow
Coding Tips

Random Numbers in Stateflow

The rand() function in Stateflow is typically used to calculate random numbers in a state and not in the evaluation of a transition. In the figure below you can see the correct and incorrect usages of rand(). In the example, the goal is to wait for a evenly distributed random period of time. Using rand() during a transition will cause rand() to be called each time that the transition is evaluated. In other words, the after() function in transition 2 compares the number of e_clk events to a different random number each time the transition is evaluated, whereas the after()function in transition 1 compares the number of e_clk events to the same random number each time that the transition is evaluated (with that same random number only changing when the TargetOn state is entered). This difference means that as time goes on, the cumulative probability that transition 2 will become true will increase relative to transition 1. So transition 2 will usually be true before transition 1 and you will not get an evenly distributed wait period from 0-500 ms. Instead you will get a wait period from 0-500 ms that is highly skewed to lower values.

Figure 10.26: Using rand() in Stateflow

The function rand() returns a double between 0 and 1. In the initial state of the Stateflow chart the random number generator is seeded using the seed provided by Dexterit-E (the seed is obtained from the From tag “seed”). Dexterit-E provides a new random seed each time a task is run. When a Task Protocol is created in Dexterit-E, the default behaviour is for this seed to come from the current time, however, there is an option in the Task Protocol to use a constant seed such that the same sequence of random numbers is used each time a task is run.

Any of the standard MATLAB random number generating functions can be used in Stateflow.

Attention: The above syntax is for Stateflow charts using MATLAB as the action language. If your Stateflow chart uses C as the action language then you will need to refer to earlier versions of this guide for instructions on using random numbers.

Related Tasks

Coding Tips
Persistent Variables
Persistent variables are ones that hold their value between calls to the embedded MATLAB code they are defined in.
Coding Tips
Custom Control of the Trial Protocol Order
Normally, Dexterit-E manages and controls the order in which Trial Protocols (TPs) execute based on what is defined in the block table of the Task Protocol (see the Dexterit-E User Guide for more details).