Using APL’s Transpose Operator ⌶ to Reorder Tensor Axes Efficiently
Learn how APL’s transpose operator ⌶ reorders tensor axes with a single symbol, avoiding verbose loops and gaining speed.
20 Mar 2026, 00:29 UTC

Problem: Re‑ordering axes in multi‑dimensional data
When working with tensors, programs often need to change the order of dimensions – for example, moving the second axis to the front. In languages that lack a built‑in tensor primitive, this is usually done with nested loops or calls to library functions that copy data element‑by‑element. The resulting code is verbose, easy to get wrong, and can dominate runtime for large arrays.
APL’s array model
APL treats everything as an array. An array’s rank is the number of axes, and its shape (retrieved with ⍴) is a vector of the lengths of those axes. Axes are numbered from 1 up to the rank, matching the order in the shape vector. This uniform model lets a single primitive operate on any rank without special‑casing.
The transpose primitive ⌶
The dyadic form A ⌶ B takes a left‑hand argument A that is a permutation of axis numbers and returns B with those axes reordered accordingly. If the left argument is omitted, the monadic form ⌶B reverses the axes (equivalent to (⌽⍳⍴⍴B) ⌶ B). Because the operation is implemented as a primitive in the interpreter, it can rearrange the internal strides without copying elements when the underlying storage permits it.
Worked example: turning a 4×5×6 tensor into 5×4×6
Suppose we have a random 3‑D array data with shape 4 5 6. To swap the first two axes we supply the left argument 2 1 3 (meaning: new axis 1 comes from old axis 2, new axis 2 from old axis 1, axis 3 stays unchanged).
data ← ? 4 5 6 ⍴ 100 ⍝ generate a 4×5×6 array of random integers shapeBefore ← ⍴ data ⍝ → 4 5 6 transposed ← 2 1 3 ⌶ data ⍝ reorder axes shapeAfter ← ⍴ transposed ⍝ → 5 4 6The expression
2 1 3 ⌶ datayields an array whose logical shape is5 4 6. No explicit loop is needed; the interpreter handles the axis permutation.Trade‑offs, verification and next steps
While the notation is concise, it can be opaque to newcomers. Supplying an invalid axis number (e.g., a duplicate or a value outside
1…rank) results in aDOMAIN ERRORin most APL implementations, so testing the left argument with⍳⍴⍴dataor a simple validation function is advisable.To confirm correctness, run the script in an APL interpreter such as Dyalog APL 18.0+ or GNU APL and compare
shapeBeforeandshapeAfterwith⍴. For a performance check, create a large array (e.g.,? 1000 1000 10 ⍴ 0) and measure the transpose primitive versus an explicit loop using⎕TIMEor⎕MM. The primitive typically shows a lower elapsed‑time ratio because it works on strides rather than copying each element.Finally, consult the language reference (e.g., Dyalog APL Language Reference, section 6.2.1) for the exact definition of ⌶ to ensure the behavior matches your expectations.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.