0

Suppose I have a vector of integers like this:

A = [1 2 3] 

What I need is nth permutation of vector A. As we now a vector of n numbers has n! permutation, For example some permutation of A is:

[1 2 3] [1 3 2] [2 1 3] [2 3 1] ... 

Is there any built-in function for calculating nth permutation? if not, can anyone please offer me a efficient algorithm for calculate it? Any suggestion would be highly appreciated

1
  • 1
    perms([1 2 3])? For N, perms(1:N), I think might work. Commented Mar 7, 2014 at 10:33

4 Answers 4

1

I found my answer from @Divakar comment (special thanks to @Divakar)
What I need is:

% this my vector 1, 2, 3 , ..., N A = 1 : N; P = perms(A); % nth permutation of A is nth row of P nthPerm = P(n, :); 
Sign up to request clarification or add additional context in comments.

Comments

0

If A is just the trivial sequence 1:N, as @Divakar said, the command

perms(1:N) 

produces the permutations you need.

If A is an array whose content is generic and whose length is N, perms can be used to obtain the indices allowing the permutations, i.e.

A_permutations = A(perms(1:N)) 

Example:

given

A = 3 7 9 A(perms(1:3)) 9 7 3 9 3 7 7 9 3 7 3 9 3 7 9 3 9 7 

Comments

0

perms(v) works for the n! case,

http://www.mathworks.de/matlabcentral/fileexchange/11462-npermutek/content/npermutek.m works for the n^n or n^k case.

Comments

0

If you like doing stuff in less lines of code, you can also do:

A=1:N; nthPerm=getfield(perms(A),{n,A}) 

Note that this is only valid if A=1,2,3,...,N. For different values of A, you would have to change this into:

A=1:N; nthPerm=getfield(perms(A),{n,1:length(A)}) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.