This blog is under construction

Saturday, 27 July 2013

C program to perform strassen's matrix multiplication

Write a C program to perform Strassen's matrix multiplication(order 2).


  #include <stdio.h>

  int main() {
        int i, j, n = 2;
        int mat1[2][2], mat2[2][2], res[2][2], m[7];

        /* get the entries for first input matrix */
        printf("Enter your input for first matrix(2X2):\n");
        for (i = 0; i < n; i++) {
                for (j = 0; j < n; j++) {
                        scanf("%d", &mat1[i][j]);
                }
        }

        /* get the entries for second input matrix */
        printf("Enter your input for second matrix(2X2):\n");
        for (i = 0; i < n; i++) {
                for (j = 0; j < n; j++) {
                        scanf("%d", &mat2[i][j]);
                }
        }

        /* straussen's matrix multiplication */
        m[0] = (mat1[0][0] + mat1[1][1])* (mat2[0][0] + mat2[1][1]);
        m[1] = (mat1[1][0] + mat1[1][1]) *  mat2[0][0];
        m[2] = (mat1[0][0]) * (mat2[0][1] - mat2[1][1]);
        m[3] = (mat1[1][1]) * (mat2[1][0] - mat2[0][0]);
        m[4] = (mat1[0][0] + mat1[0][1]) *  (mat2[1][1]);
        m[5] = (mat1[1][0] - mat1[0][0]) * (mat2[0][0] + mat2[0][1]);
        m[6] = (mat1[0][1] - mat1[1][1]) * (mat2[1][0] + mat2[1][1]);

        res[0][0] = m[0] + m[3] - m[4] + m[6];
        res[0][1] = m[2] + m[4];
        res[1][0] = m[1] + m[3];
        res[1][1] = m[0] - m[1] + m[2] + m[5];

        /* print the resultant matrix */
        printf("Resultant Matrix:\n");
        for (i = 0; i < n; i++) {
                for (j = 0; j < n; j++) {
                        printf("%d ", res[i][j]);
                }
                printf("\n");
        }

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input for first matrix(2X2):
  2  4
  2  4
  Enter your input for second matrix(2X2):
  4  2
  4  2
  Resultant Matrix:
  24 12 
  24 12 


No comments:

Post a Comment