0

I want to make 1000 random permutations of a vector in matlab. I do it like this

% vector is A
num_A = length(A);

for i=1:1000
  n = randperm(num_A);
  A = A(n); % This is one permutation
end

This takes like 73 seconds. Is there any way to do it more efficiently?

Yvon
  • 2,903
  • 1
  • 14
  • 36
user34790
  • 2,020
  • 7
  • 30
  • 37
  • Your code actually seems pretty straight-forward. `randperm` would be the way to go; I'm not sure that a better solution exists. – Roney Michael Aug 06 '14 at 17:22

2 Answers2

1

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);
Community
  • 1
  • 1
Yvon
  • 2,903
  • 1
  • 14
  • 36
0
A = perms(num_A)
A = A(1:1000)

Perms returns all the different permutations, just take the first 1000 permutations.

lakshmen
  • 28,346
  • 66
  • 178
  • 276