1
\$\begingroup\$

Suppose I have a class of complex numbers called Complex and I wish to implement a class of generic matrices with transpose operation.

doubles and ints don't require special care, but you have to calculate the conjugate of complex numbers to transpose. Therefore, I implemented a "specialized transpose()".

template <class T> 
Matrix<T> Matrix<T>::transpose() const
{
    Matrix<T> matrix(_cols, _rows);

    unsigned int i, j;

    for (i = 0; i < _rows ; ++i)
    {
        for (j = 0; j < _cols; ++j)
        {
            matrix(j, i) = (*this)(i, j);
        }
    }

    return matrix;
}

template <> 
Matrix<Complex> Matrix<Complex>::transpose() const
{
    Matrix<Complex> matrix(_cols, _rows);

    unsigned int i, j;

    for (i = 0; i < _rows ; ++i)
    {
        for (j = 0; j < _cols; ++j)
        {
            matrix(j, i) = (*this)(i, j).conj();
        }
    }

    return matrix;
}

As you can see, there's a severe code repetition. Is there any way I can deal with it (like using helper methods)?

References from Wikipedia:

\$\endgroup\$
  • 1
    \$\begingroup\$ Transpose and conjugate transpose are two different operations. The normal transposition of a complex matrix works just like normal transposition for a real/int matrix. \$\endgroup\$ – Mat Sep 7 '15 at 12:48
  • \$\begingroup\$ Do you really need to make a new matrix and return it every time you do this operation? This seems very memory inefficient if you are dealing with large matrices. The other option is to simply transpose the class-matrix. \$\endgroup\$ – Winther Sep 7 '15 at 13:27
  • \$\begingroup\$ Yes, in the school excerice we're reuqired not to change the object but return a new one. \$\endgroup\$ – Alex Goft Sep 7 '15 at 13:53
  • \$\begingroup\$ By the way, specialized method - where to i implement them and how? (for example, declare in hpp and implement in cpp)? \$\endgroup\$ – Alex Goft Sep 7 '15 at 13:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.