Swapping any pair of elements
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (1)
Athul Prakash
le 24 Oct 2019
Modifié(e) : Athul Prakash
le 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.
0 commentaires
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!