/* This file defines the operations on class Matrix, which is
  derived from class Table.

...
------------------------------------------------------------------*/

#include "Matrix.h"

/*-----------------------------------------------------------------
This function multiplies two matrices.

   Receive: Matrix Mat1 Mat2
   Return:  Mat3, containing the product of Mat1 and Mat2.
------------------------------------------------------------------*/

#include <stdlib.h>                            // provides exit()

Matrix operator*(const Matrix& Mat1, const Matrix& Mat2)
{
  if (Mat1.Columns_ != Mat2.Rows_)            // check argument 
  {                                           //  validity
      cerr << "\n*** Mat1*Mat2: columns of Mat1 "
           << "must equal rows of Mat2\n";
      exit (-1);
  }

  Matrix                                      // use Table constructor
    Mat3(Mat1.Rows_, Mat2.Columns_);          // declare result Matrix

  TableElement                                // stores the sum of 
    Sum;                                      //  pairwise products

  for (int i = 0; i < Mat1.Rows_; i++)        // for each row in M1:
    for (int j = 0; j < Mat2.Columns_; j++)   //  for each col in M2:
    {
       Sum = 0;                               //   initialize Sum
                                              //   for each col in M1:
       for (int k = 0; k < Mat1.Columns_; k++)//     sum products
          Sum += Mat1.Grid[i][k] 
               * Mat2.Grid[k][j];

        Mat3.Grid[i][j] = Sum;                //   store Sum in M3
    }

  return Mat3;                                // return result matrix
}

