Code covered by the BSD License  

Highlights from
perms1

5.0

5.0 | 1 rating Rate this file 1 Download (last 30 days) File Size: 2.01 KB File ID: #13060

perms1

by Khaled Hamed

 

21 Nov 2006 (Updated 21 Nov 2006)

returns a single permutation of the numbers 1:n

| Watch this File

File Information
Description

PERMS1(n,b), where n is a positive integer, creates a vector with n columns containing one permutation of the numbers from 1 to n. Input b is
a number between 1 and n! which is the index of the required permutation, such that the output of PERMS1(n,b) for b from 1 to n! is equivalent to
the output from perms(1:n). The order of the permutations is, however, different (e.g.,PERMS1(n,5) does not give the fifth row of the PERMS(1:n) output).

MATLAB release MATLAB 7.3 (R2006b)
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Comments and Ratings (2)
21 Nov 2006 John D'Errico

Excellent. The author has included error checks, a description of the algorithm, many internal comments so one can understand how the code works. Each call is fast too.

Two things to beware (not the fault of the author) large values of n will still be a problem. For example,

perms1(20,2e18)

and

perms1(20,2e18+1)

will generate exactly the same result. This is an artifact of double precision in matlab. So you don't want to go above n=18 in perms1.

Secondly, perms1 does not generate its permutations in the same order as perms. I'd argue that the order chosen by perms1 is more logical than perms anyway.

Well done.

23 Nov 2006 Khaled Hamed

I have submitted a new function 'recperms' which uses a similar logic, but calculates the permutations recursively, and thus no index is needed. The code is about 2.5 times faster than perms1 (still very slow compared to perms) and avoids the problem with large indices noted by John D'Errico. Thanks John.

Please login to add a comment or rating.
Tag Activity for this File
Tag Applied By Date/Time
perms permutation single Khaled Hamed 22 Oct 2008 08:49:43

Contact us at files@mathworks.com