The RAND function in stand-alone applications generates the same numbers each time you run your application because the uniform random number generator that RAND uses is initialized to same state when the application is loaded.
You will notice that each time you start up a new MATLAB session, the random numbers returned by RAND are the same. This is because MATLAB's random number generator is initialized to the same state each time MATLAB starts up.
If you wish to generate different random values in each MATLAB session, you can use the system clock to initialize the random number generator once at the beginning of each MATLAB session.
In versions of MATLAB beginning with R2008b, the simplest way to do this is to execute the following command at the beginning of each MATLAB session:
For versions of MATLAB prior to R2008b you can execute the following commands:
In either case, it is only necessary to do this once at the beginning of each MATLAB session.
Similarly, you can execute the same command(s) in your standalone application. The code you compile might look like the following:
When you compile this to an executable, the state of the random number generator is initialized based on the system clock each time the application is run, and so the array "a" in the example above will contain a unique value each time.
Remember that it's only necessary to initialize the random number generator using the system clock once in your application.
For Matlab Coder, you have to use a slightly different approach as clock is not supported for codegen.
For example, consider
For more information about MATLAB's random number generator, you can check the documentation by executing the following command at the MATLAB command prompt: