In-place matrix transposition


In-place matrix transposition, also called in-situ matrix transposition, is the problem of transposing an N×M matrix in-place in computer memory, ideally with O additional storage, or at most with additional storage much less than NM. Typically, the matrix is assumed to be stored in row-major order or column-major order.
Performing an in-place transpose is most difficult when NM, i.e. for a non-square matrix, where it involves a complicated permutation of the data elements, with many cycles of length greater than 2. In contrast, for a square matrix, all of the cycles are of length 1 or 2, and the transpose can be achieved by a simple loop to swap the upper triangle of the matrix with the lower triangle. Further complications arise if one wishes to maximize memory locality in order to improve cache line utilization or to operate out-of-core, since transposes inherently involve non-consecutive memory accesses.
The problem of non-square in-place transposition has been studied since at least the late 1950s, and several algorithms are known, including several which attempt to optimize locality for cache, out-of-core, or similar memory-related contexts.

Background

On a computer, one can often avoid explicitly transposing a matrix in memory by simply accessing the same data in a different order. For example, software libraries for linear algebra, such as BLAS, typically provide options to specify that certain matrices are to be interpreted in transposed order to avoid data movement.
However, there remain a number of circumstances in which it is necessary or desirable to physically reorder a matrix in memory to its transposed ordering. For example, with a matrix stored in row-major order, the rows of the matrix are contiguous in memory and the columns are discontiguous. If repeated operations need to be performed on the columns, for example in a fast Fourier transform algorithm, transposing the matrix in memory may improve performance by increasing memory locality. Since these situations normally coincide with the case of very large matrices, performing the transposition in-place with minimal additional storage becomes desirable.
Also, as a purely mathematical problem, in-place transposition involves a number of interesting number theory puzzles that have been worked out over the course of several decades.

Example

For example, consider the 2×4 matrix:
In row-major format, this would be stored in computer memory as the sequence, i.e. the two rows stored consecutively. If we transpose this, we obtain the 4×2 matrix:
which is stored in computer memory as the sequence.
Position01234567
Original storage1112131421222324
Transposed storage1121122213231424

If we number the storage locations 0 to 7, from left to right, then this permutation consists of four cycles:
That is, the value in position 0 goes to position 0. Next, the value in position 1 goes to position 2, while the value in position 2 goes to position 4, and position 4 goes back to position 1. Similarly for the values in position 7 and positions.

Properties of the permutation

In the following, we assume that the N×M matrix is stored in row-major order with zero-based indices. This means that the element, for n = 0,...,N−1 and m = 0,...,M−1, is stored at an address a = Mn + m. In the transposed M×N matrix, the corresponding element is stored at the address a' = Nm + n, again in row-major order. We define the transposition permutation to be the function a' = P such that:
This defines a permutation on the numbers.
It turns out that one can define simple formulas for P and its inverse. First:
where "mod" is the modulo operation.
If 0 ≤ a = Mn + m < MN − 1, then Na mod = MN n + Nm mod = n + Nm.

Second, the inverse permutation is given by:
As proved by Cate & Twigg, the number of fixed points of the permutation is precisely, where gcd is the greatest common divisor. For example, with N = M the number of fixed points is simply N. If and are coprime, on the other hand, the only two fixed points are the upper-left and lower-right corners of the matrix.
The number of cycles of any length k>1 is given by :
where μ is the Möbius function and the sum is over the divisors d of k.
Furthermore, the cycle containing a=1 is always a cycle of maximum length L, and the lengths k of all other cycles must be divisors of L .
For a given cycle C, every element has the same greatest common divisor.

Let s be the smallest element of the cycle, and. From the definition of the permutation P above, every other element x of the cycle is obtained by repeatedly multiplying s by N modulo MN−1, and therefore every other element is divisible by d. But, since N and are coprime, x cannot be divisible by any factor of larger than d, and hence.

This theorem is useful in searching for cycles of the permutation, since an efficient search can look only at multiples of divisors of MN−1.
Laflin & Brebner pointed out that the cycles often come in pairs, which is exploited by several algorithms that permute pairs of cycles at a time. In particular, let s be the smallest element of some cycle C of length k. It follows that MN−1−s is also an element of a cycle of length k.
The length k of the cycle containing s is the smallest k > 0 such that. Clearly, this is the same as the smallest k>0 such that, since we are just multiplying both sides by −1, and.

Algorithms

The following briefly summarizes the published algorithms to perform in-place matrix transposition. Source code implementing some of these algorithms can be found in the references, below.

Accessor transpose

Because physically transposing a matrix is computationally expensive, instead of moving values in memory, the access path may be transposed instead. It is trivial to perform this operation for CPU access, as the access paths of iterators must simply be exchanged, however hardware acceleration may require that still be physically realigned.

Square matrices

For a square N×N matrix An,m = A, in-place transposition is easy because all of the cycles have length 1 or length 2. Pseudocode to accomplish this is:
for n = 0 to N - 2
for m = n + 1 to N - 1
swap A with A
This type of implementation, while simple, can exhibit poor performance due to poor cache-line utilization, especially when N is a power of two. The reason for this is that, as m is incremented in the inner loop, the memory address corresponding to A or A jumps discontiguously by N in memory. That is, the algorithm does not exploit locality of reference.
One solution to improve the cache utilization is to "block" the algorithm to operate on several numbers at once, in blocks given by the cache-line size; unfortunately, this means that the algorithm depends on the size of the cache line, and on a modern computer with multiple levels of cache it requires multiple levels of machine-dependent blocking. Instead, it has been suggested that better performance can be obtained by a recursive algorithm: divide the matrix into four submatrices of roughly equal size, transposing the two submatrices along the diagonal recursively and transposing and swapping the two submatrices above and below the diagonal. This is a cache-oblivious algorithm, in the sense that it can exploit the cache line without the cache-line size being an explicit parameter.

Non-square matrices: Following the cycles

For non-square matrices, the algorithms are more complicated. Many of the algorithms prior to 1980 could be described as "follow-the-cycles" algorithms. That is, they loop over the cycles, moving the data from one location to the next in the cycle. In pseudocode form:
for each length>1 cycle C of the permutation
pick a starting address s in C
let D = data at s
let x = predecessor of s in the cycle
while xs
move data from x to successor of x
let x = predecessor of x
move data from D to successor of s
The differences between the algorithms lie mainly in how they locate the cycles, how they find the starting addresses in each cycle, and how they ensure that each cycle is moved exactly once. Typically, as discussed above, the cycles are moved in pairs, since s and MN−1−s are in cycles of the same length. Sometimes, a small scratch array, typically of length M+N is used to keep track of a subset of locations in the array that have been visited, to accelerate the algorithm.
In order to determine whether a given cycle has been moved already, the simplest scheme would be to use O auxiliary storage, one bit per element, to indicate whether a given element has been moved. To use only O or even auxiliary storage, more complicated algorithms are required, and the known algorithms have a worst-case linearithmic computational cost of at best, as first proved by Knuth.
Such algorithms are designed to move each data element exactly once. However, they also involve a considerable amount of arithmetic to compute the cycles, and require heavily non-consecutive memory accesses since the adjacent elements of the cycles differ by multiplicative factors of N, as discussed above.

Improving memory locality at the cost of greater total data movement

Several algorithms have been designed to achieve greater memory locality at the cost of greater data movement, as well as slightly greater storage requirements. That is, they may move each data element more than once, but they involve more consecutive memory access, which can improve performance on modern CPUs that rely on caches, as well as on SIMD architectures optimized for processing consecutive data blocks. The oldest context in which the spatial locality of transposition seems to have been studied is for out-of-core operation, where the matrix is too large to fit into main memory.
For example, if d = gcd is not small, one can perform the transposition using a small amount of additional storage, with at most three passes over the array. Two of the passes involve a sequence of separate, small transpositions and one involves an in-place d×d square transposition of blocks. This is further simplified if N is a multiple of M, since only one of the two out-of-place passes is required.
Another algorithm for non-coprime dimensions, involving multiple subsidiary transpositions, was described by Catanzaro et al.. For the case where is small, Dow describes another algorithm requiring additional storage, involving a square transpose preceded or followed by a small out-of-place transpose. Frigo & Johnson describe the adaptation of these algorithms to use cache-oblivious techniques for general-purpose CPUs relying on cache lines to exploit spatial locality.
Work on out-of-core matrix transposition, where the matrix does not fit in main memory and must be stored largely on a hard disk, has focused largely on the N = M square-matrix case, with some exceptions. Recent reviews of out-of-core algorithms, especially as applied to parallel computing, can be found in e.g. Suh & Prasanna and Krishnamoorth et al..