I'm writing code for matrix multiplication of 2 matrices, with sizes n1,n2
and n2,n3
.
This is what I tried:
#include <climits>
#include <iostream>
using namespace std;
int main() {
int n1 = 3;
int n2 = 3;
int n3 = 3;
int arr1[n1][n2] = {
{1, 2, 3},
{5, 6, 7},
{9, 10, 11}
};
int arr2[n2][n3] = {
{2, 0, 0},
{0, 2, 0},
{0, 0, 2}
};
int res[n1][n3];
for (int c = 0; c < n3; c++) {
for (int r = 0; r < n1; r++) {
for (int i = 0; i < n2; i++) {
res[r][c] += arr1[r][i] * arr2[i][c]; // This is the main part
}
}
}
for (int i = 0; i < n1; i++) {
for (int j = 0; j < n3; j++) {
cout << res[i][j] << ' ';
}
cout << endl;
}
return 0;
}
The output was:
6422058 1877910233 1878006934
1878000406 20 7022734
7022746 68 22
Then I tried to change the line which had +=
:
int res[n1][n3];
for(int c = 0; c < n3; c++){
for(int r = 0; r < n1; r++){
int val = 0;
for(int i = 0; i < n2; i++){
val += arr1[r][i] * arr2[i][c]; // Here I used new variable val
}
res[r][c] = val;
}
}
The problem disappeared. Output:
2 4 6
10 12 14
18 20 22
Why did this fix the problem?