Swapping any pair of elements

5 views (last 30 days)
asdfgl11
asdfgl11 on 17 Oct 2019
Edited: Athul Prakash on 24 Oct 2019
Hi,
I need to swap pair elements of a vector. For example, x=[A B C D E]
the first swap would be (1,2) (position 1 to 2) --> x=[B A C D E]
the second swap would be (1,3)--> x=[B C A D E]
the third swap would be (1,4)--> x=[B C D A E]...
the swap (3,5) would be --> x=[A B D E C] and so on... with all the combinations.
The swap (2,1) x=[ B A C D E] would be ignored because is the same as (1,2) so in total for the vector X there are 16 possible combinations. Any one can help me out? Thanks in advance
  3 Comments
asdfgl11
asdfgl11 on 17 Oct 2019
The question is how to have a matrix with all the 16 possible combiantions (if the vector increases the length, there will be more combinations).
x([1 3]) != x([3 1]); because:
[B C A D E]!= [C A B D E]
The point is to put the element at the position 1 to the position 3 is not equal putting the element at the position 3 to the position 1.
It would be the same if they're consecutive as (1,2)=(2,1) (2,3)=(3,2)... only one of them should be considered.
I've written A B C D E in order to make it easier visually but they will be numbers 1 2 3 4 5.
Here is the final matrix:
matrix.PNG

Sign in to comment.

Answers (1)

Athul Prakash
Athul Prakash on 24 Oct 2019
Edited: Athul Prakash on 24 Oct 2019
Try this:
(I used logical indexing to copy from a base matrix to resultant matrix. Got the answer by caculating the right indices to copy with)
i5 = logical(eye(5));
base = categorical({'A', 'B', 'C', 'D', 'E'});
base = repmat(base, [5 1 5]);
base_idx = permute(repmat(i5, [1 1 5]), [3 2 1]);
res = base;
res(:) = '_';
res_idx = repmat(i5, [1 1 5]);
res(res_idx) = base(base_idx);
res(~res_idx) = base(~base_idx);
% result contains 25 combinations because [A B C D E] would be included, 5 times.
% each combination is stored along a row.
% deleting all [A B C D E] combinations
del_idx = permute(repmat(i5, [1 1 5]), [1 3 2]);
res(del_idx) = [];
res = reshape(res, [4 5 5])
%result still contains 20 combinations - swaps like (2,1) and (1,2) are still included separately.
% now to reduce from 20 to 16 . . .
res = permute(res, [2 1 3]);
del_idx2 = i5(2:5, :);
res(:, del_idx2) = [];
res = reshape(res, [5 16]);
% 'res' holds the required output, with each combination stored column-wise.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!