10

I have the following problem. I need to compute the permutations of a set; however, the set may contain two elements which are the same and therefore cause repeated permutations. For example:

Given the set [ 0 0 1 2 ], the permutations include these possibilities:

 1     2     0     0
 1     2     0     0

However, I would like to avoid identical permutations such as these. In MATLAB I can simply do this:

unique(perms([ 0 0 1 2 ]), 'rows')

But the problem here is efficiency - I am doing this repeatedly in a huge for loop and the sorting required by unique is too slow. So my question is: can I compute unique permutations of this nature directly without having to loop through the result afterwards? I am working in MATLAB but just a general solution would probably be helpful, although something which can be vectorized in MATLAB would probably be ideal!

As far as I can see existing questions do not cover exactly this problem, but apologies if this has been answered before.

m.s.
  • 16,063
  • 7
  • 53
  • 88
devrobf
  • 6,973
  • 2
  • 32
  • 46
  • What problem are you really trying to solve? Why do you have a loop in which you need to find permutations of different arrays at high speed? – nibot Oct 28 '12 at 14:42
  • Good point, perhaps I should have been more specific, although it gets a bit messy. I'm finding ways of corresponding sets of objects between images, although the objects have a class associated with them. I take 5 objects from at a time from set A, and find all the ways of corresponding them to objects in set B. I tackle the class restrictions by finding permutations within each class. This is why there are zeros: they represent an object not being paired to another, which is why I do not want to repeat such permutations. – devrobf Oct 28 '12 at 14:55

1 Answers1

3

It would appear this is a regularly occurring problem. Here is a file by John d'Errico (uniqueperms) that seems to tackle it pretty effectively. As an alternative, there is another FEX submission here by Ged Ridgway; you'll have to profile a bit to see which one is faster.

Note that due to the limitations of Matlab's JIT, loops are not accelerated if they call non-builtin functions, so it might be beneficial to copy-paste the contents of these functions (and/or specialize them a bit) inside your loop(s).

Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96