Multiplication of two matrix (indexes like one dimensional array)

Viewed 103

I have class with

double *matrix;
int _row;
int _col;

in loop:

for (int i = 0; i < _row; i++) {
        for (int j = 0; j < _col; j++) {
            matrix[i * _col + j] = 0.0;
        }
}

I need to multiply two matrix and get a new one:

Matrix MatrixOperations::Mul(const Matrix &m1, const Matrix &m2) {
if (m1.CheckMul(m2)) {
    Matrix temp(m1._row, m2._col);
    for (int i = 0; i < temp._row; i++) {
        for (int j = 0; j < temp._col; j++) {
            for (int k = 0; k <= temp._col; k++) {
                temp.matrix[i * temp._col + j] += m1.matrix[i * temp._col + k] * m2.matrix[k * temp._col + j];
            }
        }
    }
    return temp;
}
}

The code is incorrect. I think the indexes are wrong, but I can't understand nor see which ones.

Does anyone have any idea? Thanks.

2 Answers

For the k-loop, it should be used the common dimension, not temp._col. Also note that the condition k <= number_of_columnsleads to an out-of-bounds access.

Matrix MatrixOperations::Mul(const Matrix &m1, const Matrix &m2)
{
    if (m1._col != m2._row) // Assuming that's what '!m1.CheckMul(m2)' does
    {
        throw std::runtime_error("The inner dimensions should be the same");
    }

    Matrix temp(m1._row, m2._col);
    for (int i = 0; i < temp._row; i++)
    {
        for (int j = 0; j < temp._col; j++)
        {
            for (int k = 0; k < m1._col; k++)
            {
                temp.matrix[i * temp._col + j] += m1.matrix[i * m1._col + k] * m2.matrix[k * m2._col + j];
            }
        }
    }
    return temp;
}

Also note that in OP's code, when the initial condition is false, the function doesn't return anything.

Here m1.matrix[i * temp._col + k] * m2.matrix[k * temp._col + j]; You're dereferencing the item in matrix m1, but using temp._col to specify the number of columns in matrix m1, you need to be using m1._col, also when dereferencing the item of m2, you should again be using m2._col, but that's the same as temp._col so it only matters from a readability standpoint

Related