Swapping any pair of elements
1 回表示 (過去 30 日間)
古いコメントを表示
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 件のコメント
回答 (1 件)
Athul Prakash
2019 年 10 月 24 日
編集済み: Athul Prakash
2019 年 10 月 24 日
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 件のコメント
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!