I am looking for a library routine callable from C++ to do an inplace matrix transpose. And I would like it done fast. Arbitrary size 2d dense matrices need to be supported.

By in-place, I mean not much extra storage should be allocated. Using a full size temporary does not count.

Eigen's has an transposeInPlace only has the effect of an in-place transpose. It still uses a full copy's worth of memory (when not square).

MKL's imatcopy does work inplace but it does so very slowly. On about 1GB input: omatcopy, 00.2s; imatcopy, 32.5s.

I've seen a few academic papers but I've not found usable code.

A permissive licences is preferred, but not required.

1 Answer 1


In-place transpose for a rectangular m x n matrix in C++.

#include <algorithm>
template<typename T>
    inline void transpose(T* A, long m, long n)
        if (m<n) std::swap(m, n);
        while (m > 1 && n > 1)
            for (long i = 1; i < m; i++)
                std::rotate(A+i, A+i*n, A+i*n+1);
            A += m;
            n -= 1;

Based on the ideas laid out here. Probably a much faster way would be using FFTW, as described here.

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.