Usually if in every iteration you need to generate a random number, it's better to generate all the random numbers once at the beginning and then in each iteration, you retrieve the number you generated from the table.
However, I encounter a problem today which against this intuition. I have a numeric vector of length N, in each iteration, I have to reshuffle the order of this vector and do something.
I implement 2 ways: the first one is exactly as I just described, i.e., in each iteration, I call function
V = randperm(N)
In the 2nd method, before the loop, I call function
W = arrayfun(@(x)randperm(N),(1:T-1)','UniformOutput',0);
W = cell2mat(W);
Here T is the total number of iterations. Then in each iteration, I just retrieve the row from the matrix W. Then the rest of the code for 2 methods are exactly the same.
However, I find the 2nd code is much slower than the 1st one (I checked that the command of "W = arrayfun(@(x)randperm(N),(1:T-1)','UniformOutput',0);" does not take much time ). I run the profiler, I find that in the 2nd code call the function "ismember>ismemberR2012a" 3 times more than the 1st code. I couldn't figure out why
Aucun commentaire:
Enregistrer un commentaire