Advertisement
steverobinson

Matrix Multiplication

Aug 5th, 2011
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.66 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. /*
  4. *   Program multiply two matrices
  5. *   @author Steve Robinson
  6. *   @see footyntech.wordpress.com
  7. */
  8.  
  9. class MatMul
  10. {
  11.     public static void main(String arg[])
  12.     {
  13.         int m,n,i,j;
  14.         Scanner in=new Scanner(System.in);
  15.        
  16.         System.out.println("Enter the order of the first matrix [row, col]: ");
  17.         m=in.nextInt();
  18.         n=in.nextInt();
  19.         int[][]matA=new int[m][n];
  20.         System.out.println("Enter the elements of the matrix [row by row]: ");
  21.         for(int a=0;a<m;a++)
  22.             for(int b=0;b<n;b++)
  23.                 matA[a][b]=in.nextInt();
  24.        
  25.         System.out.println("Enter the order of the second matrix [row, col]: ");
  26.         i=in.nextInt();
  27.         j=in.nextInt();
  28.        
  29.         if(n!=i)
  30.         {
  31.             System.out.println("Invalid order. Multiplication Impossible!");
  32.             System.exit(0);
  33.         }
  34.        
  35.         int[][]matB=new int[i][j];
  36.         int[][]matR=new int[m][j];
  37.         System.out.println("Enter the elements of the second matrix [row by row]: ");
  38.         for(int a=0;a<i;a++)
  39.             for(int b=0;b<j;b++)
  40.                 matB[a][b]=in.nextInt();
  41.                
  42.         System.out.println("\nThe Matrix 1:");
  43.         for(int a=0;a<m;a++)
  44.         {
  45.             for(int b=0;b<n;b++)
  46.                 System.out.print(matA[a][b]+" ");
  47.             System.out.println();
  48.         }
  49.        
  50.         System.out.println("\nThe Matrix 2:");
  51.         for(int a=0;a<i;a++)
  52.         {
  53.             for(int b=0;b<j;b++)
  54.                 System.out.print(matB[a][b]+" ");
  55.             System.out.println();
  56.         }
  57.        
  58.         for(int a=0;a<m;a++)
  59.             for(int b=0;b<j;b++)
  60.             {
  61.                 matR[a][b]=0;
  62.                 for(int c=0;c<n;c++)
  63.                     matR[a][b]+=matA[a][c]*matB[c][b];
  64.             }
  65.        
  66.         System.out.println("\nThe Result of Multiplication:");
  67.         for(int a=0;a<m;a++)
  68.         {
  69.             for(int b=0;b<j;b++)
  70.                 System.out.print(matR[a][b]+"  ");
  71.             System.out.println();
  72.         }
  73.        
  74.        
  75.     }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement