Matrix Multiplication In C

前端 未结 8 2265
后悔当初
后悔当初 2021-02-10 00:01

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

8条回答
  •  余生分开走
    2021-02-10 00:41

    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");
    }
    

提交回复
热议问题