Matrix Multiplication in C: Logic Explained

Matrix Multiplication: C Program

Matrix Multiplication is very easily done in MATLAB and Python as there are in-build operators and functions are available. Here a basic C program is explained in detail so that the matrix-multiplication logic architecture is understood easily. 

 

Figure 1

  

 

Figure 1 is very well self-explanatory. We take M1 & M2 two matrices input from the user and their multiplication result is stored in M3 Matrix. In matrix M1 the we first sweep the columns for the first row and in M2 the rows are swept along the first column. The sum of the multiplications is the first element of the first row of the M3 matrix. Then keeping the first row fixed for the first M1 we change the columns of the M2 matrix, this is our second sweep. The final values are stored in the M3 matrix in first-row sweeping columns, this is the same as the previous second sweep. Finally, we sweep the rows in M1 as well as in M3 this is the third sweep. Three nested for loops are used and the orders are shown in the top right and bottom left corner of the above figure.

 

Main Multiplication Code:

 

 for(i=0;i<3;i++)
{ for(k=0;k<3;k++)
{
sum=0;
for(j=0;j<3;j++)
{
sum+=mat1[i][j]*mat2[j][k];
}
mat3[i][k]=sum;
}

 

Complete Code in C:

 

 #include<stdio.h>
void main()
{
int mat1[3][3],mat2[3][3],mat3[3][3];
int i,j,k,sum;
printf("Enter Matrix 1:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{ printf("M1_(%d%d)=",i,j);
scanf("%d",&mat1[i][j]);
}
}
printf("Enter Matrix 2:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{ printf("M2_(%d%d)=",i,j);
scanf("%d",&mat2[i][j]);
}
}

for(i=0;i<3;i++)
{ for(k=0;k<3;k++)
{
sum=0;
for(j=0;j<3;j++)
{
sum+=mat1[i][j]*mat2[j][k];
}
mat3[i][k]=sum;
}
}

printf("Matrix1:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",mat1[i][j]);
}
printf("\n");
}

printf("Matrix2:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",mat2[i][j]);
}
printf("\n");
}

printf("Matrix3:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",mat3[i][j]);
}
printf("\n");
}

}

 

Input-Output:

 

 

 

Comments