Reputation: 21
I wrote a method that multiplies matrices. It works fine, but gives additional column of zeros. The result of multiplying is correct. Here is the code of method:
Matrix Matrix::multiplyMatrix(Matrix second)
{
vector<vector<double> > sum(vec.size(), vector<double> (vec[0].size()));
if (vec[0].size()!=second.vec.size())
{
throw "Dimensions are not correct";
}
else
{
for (int i=0; i<vec.size(); i++)
{
for (int j=0; j<second.vec[0].size(); j++)
{
sum[i][j]=0;
for (int k=0; k<vec[0].size(); k++)
{
sum[i][j]+=vec[i][k]*second.vec[k][j];
}
}
}
Matrix out(vec.size(), vec[0].size());
out.vec=sum;
return out;
}
}
From main:
Matrix A("A.txt",3,4);
Matrix B("B.txt",4,3);
auto C=A.multiplyMatrix(B);
C.write("C.txt");
Matrices:
A:
2 3 4 4
1 2 4 6
1 1 0 1
and
B:
1 2 3
5 6 7
9 1 5
4 5 5
Instead of 3x3 matrix it gives:
69 46 67 0
71 48 67 0
10 13 15 0
Do you know what is the problem? Thanks
Upvotes: 0
Views: 38
Reputation: 124
Your matrix named "out" has the wrong dimensions, also, int the first line of your code, the sum has wrong dimensions too.
the first line should change to:
vector<vector<double> > sum(vec.size(), vector<double> (second.vec[0].size()));
the definition of out should change to:
Matrix out(vec.size(), second.vec[0].size());
Upvotes: 1