简体   繁体   English

Matlab中的置换功能

[英]Permutations function in Matlab

In Wolfram Mathematica,there is a function called Permutations ( http://reference.wolfram.com/mathematica/ref/Permutations.html ). 在Wolfram Mathematica中,有一个名为Permutations的函数( http://reference.wolfram.com/mathematica/ref/Permutations.html )。 It can gives all permutations containing exactly n elements. 它可以给出包含正好n个元素的所有排列。

For example: Permutations[{1,2,3,4}, {2}] gives 例如: 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}}

I know Matlab have a similar function perms , but it only receive one parameter and gives all possible permutations. 我知道Matlab具有类似的函数perms ,但是它只接收一个参数并给出所有可能的排列。 Is there other function like Mathematica's Permutations[list,{n}] 还有其他功能,例如Mathematica的Permutations[list,{n}]

If order doesn't matter, take a look at nchoosek . 如果顺序无关紧要,请查看nchoosek

If it does (which seems to be the case), there is an inefficient, ugly, but non-toolbox dependent one-liner: 如果确实如此(似乎是这种情况),则存在效率低下,丑陋但不依赖于工具箱的单行代码:

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

(which is really a hacked two-liner ). (这实际上是一个被黑的两层线 )。

I'd suggest you just use combnk from the Statistics toolbox. 我建议您只使用统计工具箱中的combnk

You can get all the combinations of your desired size using nchoosek and then permute them using perms . 您可以使用nchoosek获得所需大小的所有组合,然后使用perms对其进行置换。 That means for permutations of length k from vector v you can use 这意味着对于向量v的长度k排列,您可以使用

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

Note that the rows of P will not be sorted and you can use sortrows to sort it: 请注意, P行将不会排序,您可以使用sortrows进行排序:

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

Using your example 用你的例子

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

returns: 收益:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM