gpt4 book ai didi

c++ - 两个矩阵的乘法(索引如一维数组)

转载 作者:太空狗 更新时间:2023-10-29 20:33:45 26 4
gpt4 key购买 nike

我有课

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

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

有人知道吗?谢谢。

最佳答案

对于k-loop,应该使用公共(public)维度,而不是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 时,该函数不会返回任何内容。

关于c++ - 两个矩阵的乘法(索引如一维数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53276557/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com