C++中使用二维向量的乘法矩阵
Multiplying Matrices using 2d Vectors in C++
我正在尝试设计一个程序,该程序使用整数向量的向量创建一个矩阵,然后将其与另一个矩阵相乘。我知道如何在纸上乘以矩阵,但当我试图在程序中实现它时,我并没有让它发挥作用。我知道这两个矩阵都是正确输入和传递的,因为我有这些函数的输出,这样我就可以调试了。当我尝试将它们相乘时,程序工作不正确。答案和元素的数量都不对。我知道我错过了什么,但不知道是什么。
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()函数的正确实现留给您。
相关文章:
- 我在二维向量中是否正确分配了内存
- 在二维向量或数组中可以存储的最大元素数是多少?
- 如何将整数字符串转换为整数的二维向量?
- 使用 C++98 标准填充二维静态向量
- C++中复向量与实向量的二维卷积
- 如何使用擦除和迭代器来删除二维向量中的项目
- 如何在二维向量c++中迭代col
- 如何在C++中将.csv文件的元素存储到二维向量中?
- std::vector::clear()ing 二维向量线程的内部向量安全吗?
- 在我为我的二维向量提供第一个值后控制台关闭
- 以C++输出二维向量
- 在 c++ 中赋值给二维向量
- 在二维向量的每一列中查找最大值
- 如何声明二维模板化类类型向量?
- 类对象初始化的二维向量
- 如何定义二维矢量哪个元素是可变大小的向量
- 有没有办法像python:np.concatenate([x,y,z],axis=1)中那样沿着列连接三个二维向量C++
- 我如何在二维向量中存储一些数组
- 我可以push_back矩形形状到继承矩形形状的类的二维向量中吗?
- 二维向量的迭代器