Mys*_*Guy 5 matlab combinations combinatorics
我希望,从给定的数组中,生成通过交换数组中每个可能的元素获得的所有数组,基本上是$\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
Run Code Online (Sandbox Code Playgroud)
在这个例子中,
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
Run Code Online (Sandbox Code Playgroud)
结果的每一行包含交换2个元素的输入.交换按字典顺序完成.所以在第一行中,元素1和2被交换; 在第二行中交换元素1和3; ......; 在最后一行中,元素3和4被交换.