How to do simple matrix multiplication

 

Simple matrix multiplication with sample java code.

How to do simple matrix multiplication



public class MatrixMultiplication {

 public static void main(String[] args) {
  
  int a[][] = new int[][] { {2,3}, {1,2}, {5,6} };
  int b[][] = new int[][] { {4,5,6}, {1,2,3} };
  
  if(a[0].length != b.length) {
   System.out.println("Multiplication not possible");
   return;
  }
  
  int c[][] = new int[a.length][b[0].length];
  
  for(int i=0;i<a.length;i++)
   for(int j=0;j<b[0].length;j++)
    for(int k=0;k<a[0].length;k++)
     c[i][j] += a[i][k] * b[k][j];
  
  for(int i=0;i<a.length;i++) {
   for(int j=0;j<b[0].length;j++)
    System.out.print(c[i][j] + " ");
   System.out.println();
  }
 }
}


OUTPUT:


11   16    21 
6    9     12 
26   37   48 

No comments:
Write comments