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

Multiplying Matrices using 2d Vectors in C++

本文关键字:向量 二维 C++      更新时间:2023-10-16

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

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;
}

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

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

for i in result column
 for j in result row
   res[i, j] = multiply(m1, m2, i, j)

其中乘法函数是嵌套循环,类似于以下内容:

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);

将multiply()函数的正确实现留给您。