0
$\begingroup$

(This question comes from How to swap multiple columns at once directly?)

In:
(list = Array[x, {2, 6}]) // MatrixForm
Insert[
    Drop[list, None, {2, 3}] // Transpose,
    (*→*) list[[All, 2 ;; 3]] (*←*),
    4
] // Transpose // MatrixForm
Out:

Question

How to deal with Insert the part — (*→*)...(*←*) "elegantly"?

Requirements

  1. Using Insert.
  2. Don't let the {} get involved in when passing parameters instead of removing them later.
$\endgroup$
1
$\begingroup$

Using Unevaluated[]:

list = Array[C, {2, 6}];

t = list[[All, 2 ;; 3]];
r = Drop[list, None, {2, 3}];

Insert[r // Transpose, Unevaluated[Sequence @@ Transpose[t]], 4] // Transpose
   {{C[1, 1], C[1, 4], C[1, 5], C[1, 2], C[1, 3], C[1, 6]},
    {C[2, 1], C[2, 4], C[2, 5], C[2, 2], C[2, 3], C[2, 6]}}
$\endgroup$
4
$\begingroup$

E.g. add FlattenAt

FlattenAt[Transpose@Insert[Transpose@Drop[lis, None, {2, 3}], lis[[All, 2 ;; 3]], 4], {{1, 4}, {2, 4}}]
% // MatrixForm

$\left( \begin{array}{cccccc} x(1,1) & x(1,4) & x(1,5) & x(1,2) & x(1,3) & x(1,6) \\ x(2,1) & x(2,4) & x(2,5) & x(2,2) & x(2,3) & x(2,6) \\ \end{array} \right)$

Alternatively:

index = Insert[Drop[Range[6], {2, 3}], {2, 3}, 4] //
          Replace[#, List -> Sequence, {2}, Heads -> True] &;
MatrixForm[lis[[All, index]]]
$\endgroup$
1
  • $\begingroup$ For FlattenAt method — How to expediently handle a case that contains many columns? $\endgroup$
    – ooo
    Feb 5 '18 at 9:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.