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
Here is the matrix multiplication code I use:
for(i=0;i<M;i++){
for(j=0;j<K;j++){
matC[i][j]=0;
for(k=0;k<N;k++){
matC[i][j]+=matA[i][k]*matB[k][j];
}
}
}
big thing is setting the answer matrix to zero (as the rest have said without code).
matC initially contains some garbage values. Iniatialize the martix to all zeroes. This might solve your problem
If size and dependencies don't matter I would suggest using the GNU Scientific Library. See here for features: http://en.wikipedia.org/wiki/GNU_Scientific_Library
It contains optimized routines for mathematical calculations and is quite fast with some compiler optimizations.
Already used it successful for matrix operations in 3D Development.
You must initialize elements of C
to zero first.
The problem is that in the line
matC[i][j] += matA[i][k] * matB[k][j];
you are adding things to matC, but when you create it, you don't initialize it, so it has garbage.
You sould do something like:
int matC[2][2] = {0}
which will initialize all the matrix with 0's
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");
}