Swapping any pair of elements

조회 수: 1 (최근 30일)
asdfgl11
asdfgl11 2019년 10월 17일
편집: Athul Prakash 2019년 10월 24일
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
asdfgl11
asdfgl11 2019년 10월 17일
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

댓글을 달려면 로그인하십시오.

답변 (1개)

Athul Prakash
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.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by