You can use this:
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
In this example
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
Each line of the result contains an input with two elements replaced. Transactions are performed in lexicographical order . Therefore, in the first row, elements 1 and 2 are interchanged; in the second line, elements 1 and 3 are replaced; ...; on the last line, items 3 and 4 are swapped.
source share