I have written a program that gives random values to two matrices and then using multiplication to print out a third matrix. Matrix 1 is 3x3 (rows, columns) and Matrix 2 is (3x2).
My output is as follows:
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
As you can see the third matrix gives an extra row / column with weird values. (97057910
etc.)
Below is my multiply function written in 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;
}
Does anyone have any suggestion on how to fix this issue? I want to remove that line of weird values and only have two columns.
vector< vector<int> > temp(nCommon);
seems suspicious, you probably meanstd::vector<std::vector<int>> temp(n1, std::vector<int>(n2));
– Jarod42