MATLAB: Swap between two sub array of an array

arrayexchangeMATLABmatrixpermutationsubarrayswapvector

Swap between two sub sequences. Position one and two are selected randomly first and then position three and four. Provided these selections do not overlap then element sequence between position one and two and element sequence between position three and four are swapped.
Example: idx1 = [2 4], idx2 = [7 10], A = [2 5 3 4 7 1 6 9 8 10 11 12] would become Anew=[2 6 9 8 10 7 1 5 3 4 11 12]
Thank you

Best Answer

If i assume that you want to swap idx which have the same length:
A = [2 5 3 4 7 1 6 9 8 10 11 12]
idx1 = [2 4];
idx2 = [7 9];
A_new = A;
A_new(idx1(1):idx1(2)) = A(idx2(1):idx2(2));
A_new(idx2(1):idx2(2)) = A(idx1(1):idx1(2))
gives:
A =
2 5 3 4 7 1 6 9 8 10 11 12
A_new =
2 6 9 8 7 1 5 3 4 10 11 12
EDIT:
This works for your example:
A = [2 5 3 4 7 1 6 9 8 10 11 12]
idx1 = [2 4];
idx2 = [7 10];
A_new = A(1:idx1(1)-1);
A_new = [A_new, A(idx2(1):idx2(2))];
A_new = [A_new, A(idx1(2)+1:idx2(1)-1)];
A_new = [A_new, A(idx1(1):idx1(2))];
A_new = [A_new, A(idx2(2)+1:end)]
result:
A =
2 5 3 4 7 1 6 9 8 10 11 12
A_new =
2 6 9 8 10 7 1 5 3 4 11 12
I did not test other examples.
Best regards
Stephan