# How to swap tensor indices without permutation?

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$.

• 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. May 28, 2015 at 11:51

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}}]]
]

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