Why do calls to "randn" in separate MATLAB Function Blocks return the same sequence of random numbers in Simulink

6 views (last 30 days)
When I implement functions using calls to "randn" in Simulink using MATLAB Function blocks, the calls to randn return the same results on each timestep. If I implement these functions in MATLAB, the sequence is different. Why is this and what is the expected behavior?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 25 Jan 2018
This behavior, while different than what would happen when calling "randn" in separate functions within MATLAB, is expected when implementing these functions as MATLAB Function Blocks in Simulink. This is because these function blocks are compiled into MEX files (binary MATLAB executable) rather than being evaluated line by line as in MATLAB. During this compilation, two identical, but independent random number generators are being created, one for each MATLAB Function block. Since they are independent, and identically seeded, the sequences they return will be identical. 
  Three potential workarounds to generate different sequences of random numbers for each run of the model are listed below. Which you choose will depend on your specific situation. See the attached model for an implementation of each of these options.
1. Save the functions that you have implemented as "MATLAB Function" blocks as MATLAB Functions somewhere on your path so they will be picked up and then add a call to them in your Simulink Model using the "Interpreted MATLAB Function" block.
This method will match the expected behavior in base MATLAB (that is a single random generator stream for all randn calls), but comes with the limitation that the simulation may be slower (since you are evaluating commands in MATLAB) and "Interpreted MATLAB Function" block can not be used in codegen.
2. Use the the Simulink block "Random Number" to generate normally distributed random numbers in Simulink and pass them into your MATLAB function blocks as input arguments. In the "Random Number" block, either set the seed with a random number (e.g. "randi(500)") or set it manually.
 
3) Include the line "coder.extrinsic('rand')" at the top of your MATLAB Function Block script. This will declare the random number generator function as extrinsic, and therefore generate a call to MATLAB's "rand" function, rather than including the code for this function inside the MEX file. Note that for this option you must pre-allocate memory for the output to allow Simulink to properly determine the size of the signal leaving the block.

More Answers (0)

Categories

Find more on Random Number Generation in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!