如何生成数组中两个元素的所有排列?

How to generate all the permutations of two elements in an array?

我想从给定的数组中生成通过交换数组中所有可能的元素对而获得的所有数组,基本上是 $\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]

你可以使用这个:

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 被交换。