Problem 1 - Overwriting the original vector inside loop
Each time A = A(n);
will overwrite A
, the input vector, with a new permutation. This might be reasonable since anyway you don't need the order but all the elements in A
. However, it's extremely inefficient because you have to re-write a million-element array in every iteration.
Solution: Store the permutation into a new variable -
B(ii, :) = A(n);
Problem 2 - Using i
as iterator
We at Stackoverflow are always telling serious Matlab users that using i
and j
as interators in loops is absolutely a bad idea. Check this answer to see why it makes your code slow, and check other answers in that page for why it's bad.
Solution - use ii
instead of i
.
Problem 3 - Using unneccessary for
loop
Actually you can avoid this for
loop at all since the iterations are not related to each other, and it will be faster if you allow Matlab do parallel computing.
Solution - use arrayfun
to generate 1000 results at once.
Final solution
Use arrayfun
to generate 1000 x num_A
indices. I think (didn't confirm) it's faster than directly accessing A
.
n = cell2mat(arrayfun(@(x) randperm(num_A), 1:1000', 'UniformOutput', false)');
Then store all 1000 permutations at once, into a new variable.
B = A(n);
I found this code pretty attractive. You can replace randperm
with Shuffle
. Example code -
B = Shuffle(repmat(A, 1000, 1), 2);