-1

I have built a class that declares a m, n matrix with elements of different types.

template<typename T>
class Matrix {
public:
    int m, n;
    T *elements;

How would I now go about overloading an operator to multiply two matrices? I am mostly confused about dealing with matrices that can take on a variety of sizes.

I know that I will need this line but I am not sure what to do after:

Matrix<T> operator*(Matrix<T> const &b)
j.Doe
  • 7
  • 2
  • 1
    I would perhaps encode M and N into the type. Otherwise you are forced to check at run time if the matrices are compatible. (or you could do what numpy does in python and treat it as a "broadcast") – AndyG Nov 09 '17 at 17:11
  • 1
    Okay, and where do things stop working? Have you looked up how to actually do [matrix multiplication](https://en.wikipedia.org/wiki/Matrix_multiplication)? – scohe001 Nov 09 '17 at 17:14
  • 1
    Possible duplicate of [Matrix Multiplication with operator overloading](https://stackoverflow.com/questions/9347337/matrix-multiplication-with-operator-overloading) – panzerpower Nov 09 '17 at 17:14
  • You can assume that the matrices will always be compatible. – j.Doe Nov 09 '17 at 17:15
  • Yes, it will be m*n size and then I will be calculating indexes when I need to. Here is how far I have gotten for the operator overloading: Matrix operator*(Matrix const &b) – j.Doe Nov 09 '17 at 17:16
  • @AndyG But encoding the dimensions into the type constrains a lot of other things, including making runtime arbitrarily sized matrices impossible, as well as potentially leading to bloat if the OP needs a lot of different dimensions of matrix. – underscore_d Nov 09 '17 at 17:20

1 Answers1

0

The following code is untested, but it should give you an idea of how to do matrix multiplication.

I would suggest defining the operator* as a free function rather than a member function.

template<typename T>
class Matrix
{
public:
    Matrix(int r, int c)
        : rows(r)
        , cols(c)
        , elements.resize(rows * cols)
    { }

    int rows = 0, cols = 0;
    T& operator()(int i, int j) { return elements[i * ncols + j]; }
    std::vector<T> elements;
};

template<typename T>
Matrix<T> operator*(Matrix<T> const& a, Matrix<T> const& b)
{
    assert(a.cols == b.rows);
    Matrix<T> c(a.rows, b.cols);
    for (int output_row = 0; output_row < a.rows; ++output_row)
    {
        for (int output_col = 0; output_col < b.cols; ++output_col)
        {
            double sum = 0.0;
            for (int i = 0; i < a.cols; ++i)
                sum += a(output_row, i) * b(i, output_col);
            c(output_row, output_col) = sum;
        }
    }
    return c;
}
RandomBits
  • 4,194
  • 1
  • 17
  • 30