Hello guys, I am currently working on an assignment that is due in 4 days. The point is to make a program that performs matrix arithmetic (addition, subtraction and multiplication) between two matrices. I have managed to make most of the program but I am not understanding why the multiplication method is not working. The result seems to always return wild numbers like -858993452...
Suppose I make two matrices 2X2 each
they both contain 2 in each element, that is:
This is my first time dealing with overloaded operators. I don't know where the error is but I think it's in the operator * overload. I will provide code below.
Any hints/solutions/suggestions are greatly appreciated.
Matrix::Matrix(int i, int j)
{
rows = i;
columns = j;
}
void Matrix::setMatrix()
{
cout << "Please enter matrix row elements separated by space: " << endl;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
cin >> a[i][j];
}
}
}
Matrix Matrix::operator*(const Matrix& m)
{
Matrix multMatrix(rows, columns);
if (columns == m.rows)
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
for (int k = 0; k < m.columns; k++)
{
multMatrix.a[i][j] += a[i][k] * m.a[k][j];
}
}
}
}
else
{
cout << "The matrices seem to be out of order..." << endl;
cout << "please try to make them (mXn)*(nXw)." << endl;
exit(0);
}
return multMatrix;
}
ostream& operator<<(ostream& osObject, const Matrix& m)
{
for (int r = 0; r < m.rows; r++)
{
osObject << endl;
for (int c = 0; c < m.columns; c++)
{
osObject << m.a[r][c];
osObject << " ";
}
}
return osObject;
}