【问题标题】:How to generate all the permutations of two elements in an array?如何生成数组中两个元素的所有排列?
【发布时间】:2018-05-21 11:17:21
【问题描述】:

我想从给定的数组中生成通过交换数组中每个可能的元素对获得的所有数组,基本上是 $\frac{n \cdot (n-1)} {2} $。最简单的制作方法是什么?

[编辑] :例如,如果我有[1 2 3 4]数组,我会生成[1 3 2 4],[1 2 4 3],[1 4 3 2],[2 1 3 4],[3 2 1 4][4 2 3 1]

【问题讨论】:

    标签: matlab combinations combinatorics


    【解决方案1】:

    你可以用这个:

    x = [10 20 30 40]; % example input array
    t = nchoosek(1:numel(x),2); % each row defines a swapping of two elements
    ind = bsxfun(@plus, (1:size(t,1)).', (t-1)*size(t,1)); % convert to linear index
    result = repmat(x, size(t,1), 1); % initiallize result as copies of the input
    result(ind) = result(fliplr(ind)); % do the swapping in each row
    

    在这个例子中,

    result =
        20    10    30    40
        30    20    10    40
        40    20    30    10
        10    30    20    40
        10    40    30    20
        10    20    40    30
    

    结果的每一行都包含交换了 2 个元素的输入。交换按字典顺序进行。所以在第一行元素 1 和 2 被交换;在第二行中,元素 1 和 3 被交换; ... ;在最后一行元素 3 和 4 被交换。

    【讨论】:

    • 谢谢,我相信你,会尽快测试。我使用学生版时是否需要“特殊”包?
    • @MysteryGuy 不,这不使用任何工具箱
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-17
    • 2018-09-25
    • 2023-03-25
    • 2020-08-18
    相关资源
    最近更新 更多