Tuesday 22 January 2013

Matrix Multiplication Using DMA [C Source Code]

This post provides a source code for matrix multiplication by dynamically allocating memory for matrices to be multiplied and multiplication of those matrices.

#include <stdio.h>
#include <stdlib.h>

int main()
{
 int **A, **B, **C, m, n, p, q, i, j, k;
 printf("Enter the size of matrix A: ");
 scanf("%d %d", &m, &n);
 
 printf("Enter the size of matrix B: ");
 scanf("%d %d", &p, &q);
 
 if (n == p)
 {
  A = malloc(m * sizeof(int));
  B = malloc(p * sizeof(int));
  C = malloc(m * sizeof(int));
  
  for (i = 0; i < m; i++)
  {
   A[i] = malloc(n * sizeof(int));
   C[i] = malloc(q * sizeof(int));
  }
  
  for (i = 0; i < p; i++)
  {
   B[i] = malloc(q * sizeof(int));
  }
   
  printf("Enter the matrix A:\n\n");
  for (i = 0; i < m; i++)
  {
   for (j = 0; j < n; j++)
   {
    scanf("%d", &A[i][j]);
   }
  }
  
  printf("Enter the matrix B:\n\n");
  for (i = 0; i < p; i++)
  {
   for (j = 0; j < q; j++)
   {
    scanf("%d", &B[i][j]);
   }
  }
  
  for (i = 0; i < m; i++)
  {
   for (j = 0; j < q; j++)
   {
    C[i][j] = 0;
    for (k = 0; k < n; k++)
    {
     C[i][j] = C[i][j] + (A[i][k] * B[k][j]);
    }
   }
  }
  
  printf("Multiplication of given matrices is: \n\n");
  
  for (i = 0; i < m; i++)
  {
   for (j = 0; j < q; j++)
   {
    printf("%d ", C[i][j]);
   }
   printf("\n");
  }
 
  for (i = 0; i < m; i++)
  {
   free(A[i]);
   free(C[i]);
  }
  for (i = 0; i < p; i++)
  {
   free(B[i]);
  }
  free(A);
  free(B);
  free(C);
 }
 else
 {
  printf("Matrix multiplication is not possible for given size\n\n");
 }
 return 0;
}
samar@samar-Techgaun:~$ gcc -Wall -o matrix_mul matrix_mul.c
samar@samar-Techgaun:~$ ./matrix_mul 
Enter the size of matrix A: 3 2
Enter the size of matrix B: 2 3
Enter the matrix A:

1 2
3 4
5 6
Enter the matrix B:

1 2 3
4 5 6
Multiplication of given matrices is: 

9 12 15 
19 26 33 
29 40 51