How to efficiently transpose non-square matrices?

I made a matrix class and I would like to implement a transpose method:

template<typename T>
void Matrix<T>::Transpose()
{
    // for square matrices
    if(this->Width() == this->Height())
    {
        for(std::size_t y = 1; y < this->Height(); ++y)
        {
            for(std::size_t x = 0; x < y; ++x)
            {
                // the function operator is used to access the entries of the matrix
                std::swap((*this)(x, y), (*this)(y, x));
            }
        }
    }
    else
    {
        // TODO
    }
}

      

The question is how to implement the transpose method for non-square matrices without allocating a whole new matrix (the class is used for large dense matrices), but inplace. Is there a way?

+3


source to share


1 answer


The most efficient way to transpose a matrix is ​​to not transpose it at all.

It may be most efficient to design a matrix class in a way that allows sub-matrices, slices, or something to be defined in a single data buffer, further preserving the row and column spacing and offset. Then, referring to the elements, you use that data to calculate the indices. To transpose, you only need to control these exponential values.



You can take a look at the Matrix OpenCV implementation (just for functionality implementation, not class design!)

+6


source







All Articles