Hello all,
I have an issue with a class I am writing which is supposed to be able to multiple 2 matrices together.
The issue I am having is not the actual multiplication (That bit works, thanks for the pointers yesterday). The problem, or so I assume, is with my overrides as the correct result is not achieved.
This is the code in question:
class Matrix
{
public:
Matrix(void);
Matrix(int rows, int cols);
Matrix(const Matrix& m);
~Matrix(void);
Matrix& operator=(const Matrix &rhs);
Matrix operator* (const Matrix &matrix2);
private:
vector<vector<float>> _matrix;
void Copy(const Matrix& m);
};
I have taken out methods I don't think are causing the issue to save space here.
And the code for them:
// Operator Overloads
Matrix& Matrix::operator=(const Matrix &rhs)
{
if (this != &rhs)
{
Copy(rhs);
}
return *this;
}
Matrix Matrix::operator* (const Matrix &matrix2)
{
Matrix result;
result.Resize(NumRows(),matrix2.NumCols());
int i, j, k;
float sum;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
sum = 0;
for (k = 0; k < 3; k++)
{
cout << "i: " << i << " j: " << j << " k: " << k;
sum += GetM(i, k) * matrix2.GetM(k, j);
cout << " Sum: " << sum << "\n";
}
result.SetM(i, j, sum);
}
}
return result;
}
// Private Methods
void Matrix::Copy(const Matrix& m)
{
Resize(m.NumRows(), m.NumCols());
for(int i = 0; i < m.NumRows(); i++)
{
for(int j = 0; j < m.NumCols(); j++)
{
SetM(i, j, GetM(i, j));
}
}
}
If I input into the program 2 3x3 matrices, and put a breakpoint in at return result;
on operator*
, the variable result contains the correct matrix, so the program multiplies them correctly.
What happens though, in main()
is that it simply outputs 0 in every point of the matrix:
matrix3.Resize(matrix1.NumRows(),matrix2.NumCols());
matrix3 = matrix1 * matrix2;
cout << "\nMultiplied Matrix contains:\n";
for(int i = 0; i < matrix3.NumRows(); i++)
{
for(int j = 0; j < matrix3.NumCols(); j++)
{
cout << "[" << i << "][" << j << "] - " << matrix3.GetM(i, j) << "\n";
}
}
Can anyone give me an idea of where this is going wrong?