MATLAB: What is the most efficient way to initialize random numbers

generateinitializeMATLABnumbersperformancerandnrandom

I have an application where I need to generate ten million numbers.  I noticed that "randn" and "randn(1)" have different performance, as seen below.
 
tic
for i = 1:10e6; randn; end
t1 = toc
t1 =
  1.3321
tic
for i = 1:10e6; randn(1); end
t2 = toc
t2 =
  8.4596
t2 / t1
ans =
6.3507
What is the best way to initialize these random numbers?

Best Answer

Using the values of "t1" and "t2" you displayed the difference per call to "randn" is about 5.5e-7 seconds, or about half a microsecond. The difference per call is very small in absolute value but large relative to the actual time each call takes. It's only really noticeable because you're performing the operation ten million times.
 
In the 0 input case, "randn" does not need to perform any input argument checking because there are no input arguments.
 
In the 1 input case, "randn" does need to check that its one input argument is valid and to determine what that input argument represents. Asking the questions "Is the input scalar?" (yes, it is, so we know this is a call of the form "R = randn(N) returns an N-by-N matrix containing pseudorandom values drawn from the standard normal distribution.") and "does the input contain a real finite integer value?" (yes, it does, so we know "randn" should not error) is fast but not free.
 
If generating ten million random numbers is your end goal, calling "randn" ten million times to generate a scalar each time is going to be much slower than calling it once to generate a 10e6 element vector, even taking into account the extra effort required by MATLAB to allocate memory for the 10e6 element vector as opposed to the scalar.
 
Therefore, the most efficient way to generate this many random values is to use "randn" with the input arguments to specify the size. For example, for 10e6 random numbers, you could assign these to an output array as follows:
 
output = randn(1, 10e6);