2

In Wolfram Mathematica,there is a function called Permutations(http://reference.wolfram.com/mathematica/ref/Permutations.html). It can gives all permutations containing exactly n elements.

For example: Permutations[{1,2,3,4}, {2}] gives

{{1, 2}, {1, 3}, {1, 4}, {2, 1}, {2, 3}, {2, 4}, {3, 1}, {3, 2}, {3, 4}, {4, 1}, {4, 2}, {4, 3}}

I know Matlab have a similar function perms, but it only receive one parameter and gives all possible permutations. Is there other function like Mathematica's Permutations[list,{n}]

matrix42
  • 289
  • 1
  • 2
  • 12

2 Answers2

2

If order doesn't matter, take a look at nchoosek.

If it does (which seems to be the case), there is an inefficient, ugly, but non-toolbox dependent one-liner:

>> unique(builtin('_paren', perms(1:4), :,1:2), 'rows')
ans =
      1     2
      1     3
      1     4
      2     1
      2     3
      2     4
      3     1
      3     2
      3     4
      4     1
      4     2
      4     3

(which is really a hacked two-liner).

I'd suggest you just use combnk from the Statistics toolbox.

Community
  • 1
  • 1
Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96
2

You can get all the combinations of your desired size using nchoosek and then permute them using perms. That means for permutations of length k from vector v you can use

A=nchoosek(v,k);
P=reshape(A(:,perms(1:k)), [], k);

Note that the rows of P will not be sorted and you can use sortrows to sort it:

P=sortrows(reshape(A(:,perms(1:k)), [], k));

Using your example

v = 1:4;
k = 2;
A=nchoosek(v,k);
P=sortrows(reshape(A(:,perms(1:k)), [], k))

returns:

P =
     1     2
     1     3
     1     4
     2     1
     2     3
     2     4
     3     1
     3     2
     3     4
     4     1
     4     2
     4     3
Mohsen Nosratinia
  • 9,844
  • 1
  • 27
  • 52