我已经写了一个程序,给两个矩阵的随机值,然后使用乘法打印出第三个矩阵。矩阵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;
}有人对如何解决这个问题有任何建议吗?我想删除这一行奇怪的值,并且只有两列。
发布于 2015-06-23 11:10:27
你的行数和列数都混在一起了。其思想是将A( is )乘以B ( K ),下面是代码所做的工作:
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);发布于 2015-06-23 11:03:44
即使您的一个矩阵只有两列,看起来您的for-循环仍将尝试访问每一行第三列中的值。
two.data[k][j]K从0迭代到one.data.size()-1,或者0..2。
J也从0迭代到two.data.size()-1,也是0..2.
然而,根据您的描述,two矩阵的第二维范围仅为0..1。
未定义的行为。代码正在向量结束后运行,并读取垃圾。
https://stackoverflow.com/questions/31000848
复制相似问题