MATLAB: Do calls to “rand” in MATLAB Function Blocks return the same sequence of random numbers in every Simulink simulation

blockfunctionMATLABnumberrandrandomsimulink

When I my Simulink model has calls to "rand" in MATLAB Function blocks, the simulation returns the same sequence of random numbers in every simulation. If I implement these functions in MATLAB, the sequence is different. Why is this and what is the expected behavior?

Best Answer

This behavior, while different than what would happen when using "rand" across multiple function calls 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. The seed for the random number generator remains the same across each simulation since it is the same in the MEX file.
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.