简体   繁体   中英

Vector of vector multiplication (matrix multiplication) odd output

I have tried without error, [2x2] * [2x2] and [2x3] * [3x2]. The " odd one " is the output from the [3x2] * [2x3]. its output looks something like this: row 1: [9 10 11], row 2: [39 44 49], row 3: [69 78 87 0 0 0297 0]. Rows 3's output is adding elements unlike it did with the previous trials of 2x2 and the (2x3 * 3x2).

Here's a snippet of my code where I believe the problem may lie.

int sum;
outputVec.resize(vec1.size());
for(int i = 0; i < vec1.size(); i++) {
    for(int k = 0; k < vec2[i].size(); k++) {
        sum = 0;
        for(int j = 0; j < vec1[i].size(); j++) {
            sum += (vec1[i][j] * vec2[j][k]);
        }
        outputVec[i].push_back(sum);
    }
}
for(int i = 0; i < outputVec.size(); i++) {
    for(int j = 0; j < outputVec[i].size(); j++) {
        printf("%3d",outputVec[i][j]);
    }
    cout << endl;
}
for(int i = 0; i < vec1.size(); i++)
{
  for(int k = 0; k < vec2[i].size(); k++)
  ...

vec2 doesn't necessarily have as many rows as vec1 (as in the (3x2) * (2x3) case). You're reading past the end of vec2 and getting undefined behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM