【问题标题】:Permutations function in MatlabMatlab中的排列函数
【发布时间】:2013-10-22 11:33:30
【问题描述】:

在 Wolfram Mathematica 中,有一个函数叫做Permutations(http://reference.wolfram.com/mathematica/ref/Permutations.html)。 它可以给出恰好包含 n 个元素的所有排列。

例如:Permutations[{1,2,3,4}, {2}] 给予

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

我知道 Matlab 有一个类似的函数perms,但它只接收一个参数并给出所有可能的排列。有没有像Mathematica的Permutations[list,{n}]这样的功能?

【问题讨论】:

标签: algorithm matlab wolfram-mathematica permutation


【解决方案1】:

如果顺序无关紧要,请查看nchoosek

如果确实如此(似乎是这种情况),则存在一种效率低下、丑陋但不依赖工具箱的单线:

>> 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

(实际上是a hacked two-liner)。

我建议您只使用统计工具箱中的combnk

【讨论】:

  • +1 但我建议您也添加 2 行等价物以提高可读性。
【解决方案2】:

您可以使用nchoosek 获得所需大小的所有组合,然后使用perms 置换它们。这意味着您可以使用向量v 中长度k 的排列

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

注意P的行不会被排序,你可以使用sortrows来排序:

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

使用你的例子

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

返回:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    • 1970-01-01
    相关资源
    最近更新 更多