I\'m trying to solve a matrix multiplication problem with C. Matrix sizes given in problem (2x2) I wrote this code but it doesn\'t print result as I expect. I think I\'m missing
You may want to dynamically allocate memory for the resultant matrix. If so, use calloc()
to allocate and clear the elements. printMatrix()
is called
to print result, but not defined here.
/* matrix1: [rows1 x cols1]; matrix2: [rows2 x cols2]; product is
matrix3: [rows1 x cols2] if (cols1 == rows2) is true. calloc to
allocate / clear memory for matrix3. Algorithm is O(n^3) */
float ** matrix3;
if (cols1 == rows2) { // product matrix can be calculated
// calloc product matrix3
matrix3 = (float **)calloc(rows1, sizeof(float *));
for (int i = 0; i < rows1; i++)
matrix3[i] = (float *)calloc(cols2, sizeof(float));
int i, j, k;
float tmp;
for (i = 0; i < rows1; i++) {
for (j = 0; j < cols2; j++) {
tmp = 0.0;
for (k = 0; k < rows2; k++)
tmp += matrix1[i][k] * matrix2[k][j];
matrix3[i][j] = tmp;
}
}
printMatrix(matrix3, rows1, cols2, 3);
free(matrix3);
} else { // cols1 != rows2
puts("dimensional mismatch; can't multiply matrices");
}