我重载了乘以二维数组的运算符 *。我在乘法时遇到了一些问题,在乘法时不完全理解索引。
这里有一些声明:
int *const e; //pointer to the memory storing all integer elements of A
const int row, column; //r and c are the numbers of rows and columns respectively
还有一些代码:
A A::operator*(const A& matrix)const
{
MAT result(matrix.row, matrix.column);
if (column == matrix.row)
{
for (int i = 0; i < row; ++i)
{
for (int j = 0; j < matrix.column; j++)
{
result.e[j*row + i] = 0;
for (int k = 0; k < column; k++)
{
result.e[j*row + i] += e[j*row + k] * matrix.e[k*row + column];
}
}
}
}
return result;
}
我知道我需要3个循环,我想我在
result.e[j*row + i] += e[j*row + k] * matrix.e[k*row + column];
你有什么线索吗?你可以给我写一些想法,我怎么能自己弄清楚,因为我想了解它。谢谢
最佳答案
你的线路
result.e[j*row + i] += e[j*row + k] * matrix.e[k*row + column];
坏了。两个矩阵 A (dim M,N) 和 B (dim N,P) 的乘积 P 在位置 (i,j) 的系数由以下定义:
Pi,j = sum(k = 1..N, ai,k . bk,j).
因此上面提到的行应该是:
result.e[j*row + i] += e[j*row + k] * matrix.e[k*row + i];
关于c++ - 在 C++ 中乘以二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27561385/