2
$\begingroup$

Say I have a tensor of rank R, How to swap $i^{th}$ and $j^{th}$ tensor index? I do not want to use TensorTranspose because it requires to write down the entire permutation, i.e. TensorTranspose[T,{1,2,3,...,j,...i,...,R}], but for my application I don't know before hand what are the numerical values of $i$ and $j$.

$\endgroup$
1
  • $\begingroup$ Welcome to Mathematica.SE! I hope you will become a regular contributor. To get started, 1) take the introductory Tour now, 2) when you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge, 3) remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign, and 4) give help too, by answering questions in your areas of expertise. $\endgroup$
    – bbgodfrey
    May 28, 2015 at 11:51

1 Answer 1

3
$\begingroup$

If you don't know what the numerical values of $i$ and $j$, then it will be hard to implement the index swap. However, it is easy to programmatically implement the index list as an argument for TensorTranspose:

Permute[Range[1, 10], Cycles[{{2, 5}}]]

(* => {1, 5, 3, 4, 2, 6, 7, 8, 9, 10} *)

Thus, you could do something like

twoWayTranspose[T_, {i_, j_}] := TensorTranspose[T,
                                    Permute[Range[ArrayDepth[T]], Cycles[{{i, j}}]]
                                   ]
$\endgroup$
1
  • 1
    $\begingroup$ TensorTranspose understands Cycles notation. Hence you can define twoWayTranspose[T_, {i_, j_}] := TensorTranspose[T, Cycles[{{i, j}}]]. $\endgroup$
    – jose
    May 29, 2015 at 9:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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