Matlab的perms函数中的表观错误

Siv*_*ash 7 math matlab permutation discrete-mathematics elementary-functions

 p = perms([0:2])
Run Code Online (Sandbox Code Playgroud)

p =

 2     1     0
 2     0     1
 1     2     0
 1     0     2
 0     1     2
 0     2     1
Run Code Online (Sandbox Code Playgroud)

该函数应该以反向字典顺序显示向量的排列.因此,我希望此输出的最后一行包含元素0 1 2; 但是,它包含0 2 1.其他行正确显示.

简而言之,最后两行的顺序是互换的.这里发生了什么?

Lui*_*ndo 9

是的,这似乎是一个错误.接得好!但可能是文档中的错误,而不是函数中的错误.

如果您键入open perms以查看源代码,您将在第一行中看到以下说明:

%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
Run Code Online (Sandbox Code Playgroud)

其中没有提到反转字典顺序.

实际工作由递归的本地函数完成permsr.如果你看一下它的代码,它起初并不是很明显它是如何工作的(像往常一样递归),而是行

t(t == i) = n
Run Code Online (Sandbox Code Playgroud)

给出一个线索,即结果中没有寻求特定的顺序.

如果您尝试使用更大的向量,则会在更多行中看到反向词典顺序的差异:

>> 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
     ...
Run Code Online (Sandbox Code Playgroud)

总之,该功能似乎是在不考虑任何顺序的情况下设计的.声称该订单可能是错误的文档.

  • @Siva`sortrow(p)` (2认同)