我想从给定的数组生成所有数组,这些数组是通过交换数组中的每个可能的几对元素而获得的,基本上是$ \ 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被交换。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句