Matrix – Matrix Multiplication

Assume two matrices A (a n x m matrix) and B (a m x p matrix) are to be multiplied

image

the matrix product AB is defined to be the n x p matrix:

image

where

image

  • The number of columns in A (m) has to equal the number of rows in B (m).
  • The number of rows in A (n) determines the number of rows in the result AB.
  • The number of columns in B (p) determines the number of columns in the result AB.

For example,

image

Here is the C++ implementation of matrix – matrix multiplication.  The complete source code of CMatrix can be downloaded from here.

template
CMatrix CMatrix::operator*(const CMatrix & v) const
{
    assert(_columns == v._rows);

    T * data = new T[_rows*v._columns];
    if (data == NULL)
    {
        printf("errorn");
        exit(1);
    }

    for (int i = 0; i < _rows; i++)
        for (int j = 0; j < v._columns; j++)
        {
            T & val = data[i + j*_rows];
            val = 0;

            for (int k = 0; k < _columns; k++)
                val += get(i, k)*v.get(k, j);
        }

    return CMatrix(_rows, v._columns, data, true);
}

Leave a Reply