How can I reorder an array in MATLAB by a specific rule?

Suppose I have this array:

a = [1,2,3,4,5];

The result should be something like this:

1,2,3,4,5
2,1,3,4,5
3,1,2,4,5
4,1,2,3,5
5,1,2,3,4

How can i do this? This function must be valid for different lengths a.

+4
source share
4 answers

Using a combination:

b = [a.' flipud(nchoosek(a,numel(a)-1))];
+9
source

A simple solution could be:

primarySet = 1:5;
result = zeros(length(primarySet));
for i = 1: length(primarySet)
    temp = primarySet;
    temp(i) = [];
    result(i,:) = [primarySet(i) temp];
end
+3
source

Another way:

a = [10 20 30 40 50];
ind = 1:numel(a);
result = a(abs(sort(bsxfun(@times, ind, 1-2*eye(numel(ind))),2)));

gives

result =
    10    20    30    40    50
    20    10    30    40    50
    30    10    20    40    50
    40    10    20    30    50
    50    10    20    30    40
+3
source

And one more way:

n = numel(a)-1;
b = [a(:) flipud(reshape(ndgrid(a,1:n).',[],n))];

b =

     1     2     3     4     5
     2     1     3     4     5
     3     1     2     4     5
     4     1     2     3     5
     5     1     2     3     4
+2
source

Source: https://habr.com/ru/post/1680722/


All Articles