Matrix multiplication w/ random values wrong output

343 Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

You're getting your numbers of rows and columns mixed up. The idea is to multiply A (I x K) by B (K x J), and here's what the code does:

int n1 = one.data[0].size(); // this is K
int n2 = two.data.size(); // this is also K

int nCommon = one.data.size(); // this is I

vector< vector<int> > temp(nCommon);

for ( int i = 0 ; i < nCommon ; i++ )
   temp[i].resize(n2);

// temp is now I x K, which is not what was intended,
// and the iteration over rows and columns will not be correct.

Try this instead:

int n1 = one.data.size(); // this is I
int n2 = two.data[0].size(); // this is J

int nCommon = two.data.size(); // this is K

vector< vector<int> > temp(n1);
for ( int i = 0 ; i < nCommon ; i++ )
   temp[i].resize(n2);
0
On

Even though one of your matrixes has only two columns, looks like your for-loop will still attempt to access values in the third column of each row.

two.data[k][j]

k iterates from 0 to one.data.size()-1, or 0..2.

j also iterates from 0 to two.data.size()-1, also 0..2.

However, according to your description, the two's matrix's second dimension's range is only 0..1.

Undefined behavior. The code is running off past the end of the vector, and reads garbage.