Obvious error in Matlab rewind function

p = perms([0:2]) 

p =

  2 1 0 2 0 1 1 2 0 1 0 2 0 1 2 0 2 1 

This function should display permutations of the vector in reverse lexicographic order. Therefore, I would expect the last line of this output to contain elements 0 1 2 ; however, it contains 0 2 1 . The remaining lines are displayed correctly.

In short, the order of the last two lines is interchangeable. What's going on here?

+7
math matlab permutation discrete-mathematics
source share
1 answer

Yes, it seems to be a mistake. Good catch! But probably a mistake in the documentation , not in the function.

If you type open perms to see the source code, you will see the following description in the first lines:

 %PERMS All possible permutations. % PERMS(1:N), or PERMS(V) where V is a vector of length N, creates a % matrix with N! rows and N columns containing all possible % permutations of the N elements. % % This function is only practical for situations where N is less % than about 10 (for N=11, the output takes over 3 gigabytes). % % Class support for input V: % float: double, single % integer: uint8, int8, uint16, int16, uint32, int32, uint64, int64 % logical, char 

in which reference is made to the reverse lexicographical order.

The actual job is performed by the recursive local function permsr . If you look at its code, at first it’s not obvious how it works (as usual with recursion), but the line

 t(t == i) = n 

gives a clue to the understanding that the search does not require a certain order

If you try a larger vector, you will see discrepancies in the reverse lexicographic order in more lines:

 >> perms(0:3) ans = 3 2 1 0 3 2 0 1 3 1 2 0 3 1 0 2 3 0 1 2 3 0 2 1 %// here. Affects cols 1 and 2 2 3 1 0 2 3 0 1 2 1 3 0 2 1 0 3 2 0 1 3 2 0 3 1 %// here. Affects cols 1 and 2 1 2 3 0 1 2 0 3 1 3 2 0 %// here. Affects cols 2 and 3 ... 

Thus, the function, apparently, was developed without taking into account any order. This is documentation that is probably erroneous in asserting this order.

+9
source share