0

I have a two 1 by 10^3 matrix which its elements change in each step of the loop of simulation. To find a new element in each for loop step, I need 2*1000 Gaussian random numbers. the number of loop steps is equal to 10^5. Which method is less time-consuming in this case?

  1. creating two 10^5 by 1000 random matrix before for loop and call them inside the loop.

  2. creating two 1 by 10^3 random matrix in each step of the loop?

EBH
  • 10,350
  • 3
  • 34
  • 59
Oliver Range
  • 365
  • 3
  • 10

1 Answers1

0

Here is a little code to answer your question:

function rnd_time_test
rnd_test = @(n) randn(2,n,1000);
N = 1e5;
one_time = timeit(@() rnd_test(N))
loop_time = timeit(@() rnd_test_loop(N))

    function R = rnd_test_loop(n)
        for k = 1:n
            R = randn(2,1000);
        end
    end
end

and the result:

one_time =
      2.245
loop_time =
      1.6311

So, on my machine, using a loop is faster.

EBH
  • 10,350
  • 3
  • 34
  • 59