带随机值的矩阵乘法错误输出

Matrix multiplication w/ random values wrong output

我编写了一个程序,为两个矩阵赋予随机值,然后使用乘法打印出第三个矩阵。矩阵 1 是 3x3(行、列),矩阵 2 是 (3x2)。

我的输出如下:

Matrix 1:
  4   6   0
  9   1   5
  4   7   5
Matrix 2:
  4   6
  0   9
  1   5
matrix 1 x matrix 2:
 16  78 97059710
 41  88 218384285
 21 112 97059715

如您所见,第三个矩阵给出了一个带有奇怪值的额外行/列。 (97057910等)

下面是我用 C++ 编写的乘法函数:

Matrix Matrix::multiply(Matrix one, Matrix two) {

    int n1 = one.data[0].size();
    int n2 = two.data.size();

    int nCommon = one.data.size();

    vector< vector<int> > temp(nCommon);

    for ( int i = 0 ; i < nCommon ; i++ )
       temp[i].resize(n2);

    for(int i=0;i<n1;i++) {
        for(int j=0;j<n2;j++) {
            for(int k=0;k<nCommon;k++) {
                temp[i][j]= temp[i][j] + one.data[i][k] * two.data[k][j];
            }
        }
    }

    const Matrix result = Matrix(temp);
    return result;
}

有人对如何解决此问题有任何建议吗?我想删除那行奇怪的值并且只有两列。

即使您的一个矩阵只有两列,看起来您的 for 循环仍会尝试访问每行第三列中的值。

two.data[k][j]

k 从 0 迭代到 one.data.size()-1,或 0..2.

j也从0迭代到two.data.size()-1,还有0..2.

但是,根据你的描述,two的矩阵的第二维范围只有0..1.

未定义的行为。代码 运行 超出向量末尾,读取垃圾。

您混淆了行数和列数。这个想法是将 A (I x K) 乘以 B (K x J),代码的作用如下:

int n1 = one.data[0].size(); // this is K
int n2 = two.data.size(); // this is also K

int nCommon = one.data.size(); // this is I

vector< vector<int> > temp(nCommon);

for ( int i = 0 ; i < nCommon ; i++ )
   temp[i].resize(n2);

// temp is now I x K, which is not what was intended,
// and the iteration over rows and columns will not be correct.

试试这个:

int n1 = one.data.size(); // this is I
int n2 = two.data[0].size(); // this is J

int nCommon = two.data.size(); // this is K

vector< vector<int> > temp(n1);
for ( int i = 0 ; i < nCommon ; i++ )
   temp[i].resize(n2);