I'm doing a homework assignment which involves multiplying more than 2 matrices.
I thought about multiplying the first 2 matrices then take its result, continue multiplying it with the 3rd matrix, and repeat the same process until I multiply all the matrices together.
A * B * C = (A * B) * C = A * (B * C)
And here is my code so far. All of my matrices are stored in a 3D array of matrix[1][row][column]
.
// Calculate the result of first 2 matrices
for (int a = 0; a < n7; a++) {
for (int b = 0; b < n7; b++) {
for (int l = 0; l < n7; l++) {
sum += matrix[1][l][b] * matrix[0][a][l];
}
resultMatrix[a][b] = sum;
sum = 0;
}
}
// Check if k > 2, if yes then continue taking matrix[2] multiply with the result
if (k > 2) {
// Calculate to a tempResult matrix
for (int f = 2; f < k; f++) {
for (int a = 0; a < n7; a++) {
for (int b = 0; b < n7; b++) {
for (int l = 0; l < n7; l++) {
sum += matrix[f][l][b] * resultMatrix[a][l];
}
resultMatrix[a][b] = sum;
sum = 0;
}
}
// Pass the result to the original resultMatrix
for (int a = 0; a < n7; a++) {
for (int b = 0; b < n7; b++) {
resultMatrix[a][b] = tempResult[a][b];
}
}
}
}
I could not get the same result with an online matrix calculator and some manual input.
Please point out my mistakes, thank you!