首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >矩阵乘法w/随机值输出错误

矩阵乘法w/随机值输出错误
EN

Stack Overflow用户
提问于 2015-06-23 10:54:45
回答 2查看 288关注 0票数 0

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

我的产出如下:

代码语言:javascript
复制
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++编写的乘法函数:

代码语言:javascript
复制
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;
}

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-06-23 11:10:27

你的行数和列数都混在一起了。其思想是将A( is )乘以B ( K ),下面是代码所做的工作:

代码语言:javascript
复制
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.

试一试:

代码语言:javascript
复制
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);
票数 0
EN

Stack Overflow用户

发布于 2015-06-23 11:03:44

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

代码语言:javascript
复制
two.data[k][j]

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

J也从0迭代到two.data.size()-1,也是0..2.

然而,根据您的描述,two矩阵的第二维范围仅为0..1。

未定义的行为。代码正在向量结束后运行,并读取垃圾。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31000848

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档