Matrix multiplication basic

The multiplication of two matrix is possible only if one is of dimension M×N and the other is of dimension N×P where M, N, and P are positive numbers. The resulting matrix will be of dimension M×P. Based on the above limitation write a c code to multiply two matrices in c. For example 

Matrix multiplication in c                                                                     (image source: http://code.wikia.com/wiki/Matrix_multiplication)

The resulting matrix would be:

matrx

                (image source: http://code.wikia.com/wiki/Matrix_multiplication)

From above figure it shows that for matrix multiplication first we multiply and sum the first row with the first column: 2(3) + 3(2) + (-1)(-1) + 0(2). Then we do the same for the first row and second column: 2(4) + 3(1) + (-1)(2)+ 0(7), etc.

Now let us write a simple c code for above:

#include<stdio.h>

#define a_row 2
#define a_col 4
#define b_row 4
#define b_col 2

// A[2x4]B[4x2] = C[2x2]
// A[mxn]B[nxp] = C[mxp]

void multiply(int A[][a_col], int B[][b_col], int C[a_row][b_col]);

int main ()
{
  int A[][4] = { {2, 3, -1, 0},
                 {-7, 2, 1,10}};

  int B[][2] = {  {3, 4},
          {2, 1},
            {-1, 2},
            {2, 7}};
 
  int C[a_row][b_col];

  multiply(A,B,C);

    /*print result*/
       int i,j;

    for(i=0;i<a_row;i++){
    for(j=0;j<b_col;j++)
        {
        printf("%d ",C[i][j]);
    }
    printf("\n");
    }
  return 0;
}

void multiply(int A[][a_col], int B[][b_col], int C[a_row][b_col])
{
    int i=0;
    int j=0;
    int k=0;
    for ( i = 0; i < a_row; i++)
    {
        for (j = 0; j < a_col; j++)
        {
            C[i][j] = 0;
            for (k = 0; k < b_row; k++)
            {
                C[i][j] += A[i][k]*B[k][j];
            }
        }
    }
}

Time Complexity of above code is O(N3).

Ref: http://code.wikia.com/wiki/Matrix_multiplication



Related Contents to follow