用C++中的二维向量乘矩阵

用C++中的二维向量乘矩阵,c++,matrix,vector,C++,Matrix,Vector,我试图设计一个程序,使用整数向量的向量创建一个矩阵,然后将它与另一个矩阵相乘。我知道如何在纸上乘法矩阵,但当我试图在我的程序中实现它时,我无法让它工作。我知道这两个矩阵输入正确,传递正确,因为我有这些函数的输出,所以我可以调试。当我尝试将它们相乘时,程序工作不正确。答案和元素的数量都不对。我知道我遗漏了什么,但我不知道是什么 Matrix Matrix::operator*(Matrix m){ vector<int> mRow = m.getRow(0); vect

我试图设计一个程序,使用整数向量的向量创建一个矩阵,然后将它与另一个矩阵相乘。我知道如何在纸上乘法矩阵,但当我试图在我的程序中实现它时,我无法让它工作。我知道这两个矩阵输入正确,传递正确,因为我有这些函数的输出,所以我可以调试。当我尝试将它们相乘时,程序工作不正确。答案和元素的数量都不对。我知道我遗漏了什么,但我不知道是什么

Matrix Matrix::operator*(Matrix m){
    vector<int> mRow = m.getRow(0);
    vector<int> mCol = m.getCol(0);
    vector<int> newElem;
    int product = 0;

    //adds the contents of the 2nd matrix to the 2d vector
    vector< vector<int> > m2(mRow.size(), vector<int>(mCol.size()));        
    for (int i = 0; i < mRow.size(); i++){
        mRow.clear();
        mRow = m.getRow(i);
        for (int j = 0; j < mCol.size(); j++){
            m2[j][i] = mRow[j];
        }

    }

    //Multiplies the matrices using the 2d matrix**THIS IS WHERE IT GOES WRONG**
    for (int i = 0; i < row; i++){
        for (int j = 0; j < column; j++){
            product += matrix[i][j]*m2[j][i];
        }
        newElem.insert(newElem.begin()+i,product);
        product = 0;
    }

    //displays the products so that i can see if its working
    for (int i = 0; i < newElem.size(); i++){
        cout << "  "<<newElem[i]<<endl;
    }

    //adds the new product vector to a new Matrix object and returns it
    Matrix newM(row, mCol.size());
    vector<int> temp;
    for (int i = 0; i < row; i++){
        for (int j = 0; j < mCol.size(); j++){
            temp.insert(temp.begin()+j, newElem[0]);
            newElem.erase(newElem.begin()); 
        }
        newM.setRow(temp,i);
        temp.clear();
    }
    return newM;
}

虽然我不知道这是否有帮助,但我使用站点作为将两个矩阵相乘的参考。

您的矩阵表示与您的错误无关。您需要有更多的嵌套迭代。考虑一个结果矩阵,并通过它迭代计算它的每个元素。在伪代码中:

for i in result column
 for j in result row
   res[i, j] = multiply(m1, m2, i, j)
其中,multiply函数是嵌套循环,如下所示:

multiply(m1, m2, i, j)
{
  val = 0;
  for k in row
    val += m1[i, k] * m2[k, j]
 return val
}
下面是外部循环的一个实现。请注意,代码中没有错误检查

vector<vector<int> > ml;
vector<vector<int> > mr;
// fill in ml and mr
...

// result matrix
vector<vector<int> > res;

// allocate the result matrix
res.resize(ml.size());
for( it = res.begin(); it != res.end(); ++it)
  it->resize(ml[0].size());


// loop through the result matrix and fill it in
for( int i = 0; i < res.size(); ++i)
    for( int j = 0; j < res[0].size(); ++j)
       res[i][j] =  multiply(ml, mr, i, j);

将乘法函数的正确实现留给您。

您不应该在乘法的外部for循环中重置乘积吗?是的,我应该重置,这已经修复,但我仍然无法获得所需的全部结果。如果我有一个3x3*3x3,我应该得到9个元素;我只得到3。这是我的问题,我甚至不能得到伪代码的实现。就好像我有写块什么的。我不得不把它写在纸上,但在实现它的时候,我仍然没有弄清楚。