5 Matrix Mult
5 Matrix Mult
Aim:- Wap to perform the multiplication of two matrices Theory:- Matrix multiplication is best described by first defining the scaler
product of two vectors. Suppose U and V are n-element vectors. Then the scalar product of U and V written U.V . written U.V is the scalar obtained by multiplying the elements of U by the corresponding elements of V. and then adding U.V=U1V1 + U2V2 + . + UnVn = UkVk We emphasize that U.V is a scalar not a vector. Now suppose A is an mp and suppose B is a pn matrix. The product of A and B written AB, is the mn matrix C whose ijth element Cij is given by: (Where k=1 to n)
ALGORITHM:Let A be an mp (22) matrix array, and let B be a pn (22) matrix array. The product of A and B stores in an mn (22) matrix array C. 1. 2. 3. 4. Repeat steps 2 & 4 for i=1 to 2 : Repeat steps 3 & 4 for j=1 to 2: Set C[i][j] := 0 [initializes C[i][j].] Repeat for k=1 to 2: c[i][j] =c[i][j]+a[i][k]*b[k][j]; (end of inner loop) (end of step 2 middle loop.) (end of step 1 outer loop) 5. Exit.
COMPLEXITY:The complexity of matrix multiplication is measured by counting the multiplications. For the above multiplications the complexity is given by C=mnp Runtime (n3) This comes from the step 4 which contains the only multiplication is executed. Program
#include<stdio.h> #include<conio.h> void main( ) { int a[2][2], b[2][2],c[2][2]; int i,j,k; clrscr(); printf("Enter first matrix:\n\n"); for( i=1;i<=2;i++) { for( j=1;j<=2;j++) { printf("Enter a[%d%d] =\t",i,j); scanf("%d",&a[i][j]); } } printf("\n"); printf("Enter second matrix:\n\n"); for(i=1;i<=2;i++)
for(i=1;i<=2;i++) { for(j=1;j<=2;j++) { c[i][j]=0; for(k=1;k<=2;k++) { c[i][j] =c[i][j]+a[i][k]*b[k][j]; } } } printf("\n"); printf("Matrix Multiplication Is: \n"); for(i=1;i<=2;i++) { for (j=1;j<=2;j++) { printf("%d\n",c[i][j]); } } getch(); }
OUTPUT