Question

So what I am trying to do is multiply one 2d vector by another 2d vector.

I come from Java,Python and C# so I am pretty much learning C++ as I go along.

I have the code down to generate the vector and display the vector but I can't seem to finish the multiplication part.

v1 is another matrix that is already generated.

vector<vector<int> > v2 = getVector();

int n1 = v1[0].size();
int n2 = v2.size();

vector<int> a1(n2, 0);
vector<vector<int> > ans(n1, a1);

for (int i = 0; i < n1; i++) {
    for (int j = 0; j < n2; j++) {
        for (int k = 0; k < 10; k++) {
            // same as z[i][j] = z[i][j] + x[i][k] * y[k][j];
            ans[i][j] += v1[i][k] * v2[k][j];
        }
    }
}

displayVector(ans);

My guess for where I am going wrong is in the inner-most loop. I can't figure out what to actually put in place of that 10 I have there now.

Was it helpful?

Solution

When you multiply matrices, the number of columns of the matrix on the left side must equal the number of rows of the matrix on the right side. You need to check that that is true, and use that common number for your size of the k variable:

int nCommon = v1.size();
assert(v2[0].size() == nCommon);
for (int i = 0; i < n1; i++) {
    for (int j = 0; j < n2; j++) {
        for (int k = 0; k < nCommon ; k++) {
            ans[i][j] += v1[i][k] * v2[k][j];
        }
    }
}

OTHER TIPS

For you inner loop, you should do something like this

            ans[i][j] = 0;
            for (int k = 0; k < n2; k++) {               
                ans[i][j] += v1[i][k] * v2[k][j];
            }

I don't know where the 10 comes from.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top