两个矩阵的乘法(索引类似于一维数组)

3

我有一门课程需要学习

double *matrix;
int _row;
int _col;

在循环中:

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

我需要将两个矩阵相乘并得到一个新的矩阵:

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;
}
}

代码不正确。我认为索引是错误的,但我无法理解或看到哪些是错误的。

有人有任何想法吗? 谢谢。


你认为为什么“代码不正确”?运行它时会发生什么?应该发生什么?请尝试创建一个最小完整可验证示例来展示给我们。同时,请阅读关于如何提出好问题以及此问题清单的内容。最后,请学习如何调试程序 - Some programmer dude
在你的表达式中加入一些括号,以清楚地展示优先级顺序。 - SPlatten
你能展示一下矩阵的构造函数吗?(主要是内存分配)。还有,这会给你什么错误? - M.K
1
对于 k 循环,我会使用 k < m1._col 而不是 k <= temp._col - Damien
2个回答

3
对于 k 循环,应该使用常规维度而不是 temp._col。同时注意条件 k <= number_of_columns 导致越界访问。
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;
}

此外,需要注意的是,在OP的代码中,当初始条件为false时,该函数不会返回任何内容。

@Bob__ 完成了。再次感谢您。 - Damien

2

这里你在解引用矩阵m1中的项,但使用temp._col来指定矩阵m1中列的数量,你需要使用m1._col。当解引用m2中的项时,你应该再次使用m2._col,但这与temp._col相同,因此仅在可读性方面有所区别。


你确定吗?它被初始化为 Matrix temp(m1._row, m2._col) - palotasb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接