How to implement matrix multiplication in Java

2 Answers

0 votes
class Program {
    public static void main(String[] args) {
                 
        int a[][] = { { 1, 8, 5 }, { 6, 7, 1 }, { 8, 7, 6 } };
        int b[][] = { { 4, 8, 1 }, { 6, 5, 3 }, { 4, 6, 5 } };
        int[][] c = new int[a.length][a.length];
  
        Print(a);
        System.out.println();    
        Print(b);
        System.out.println();
  
        // c[0, 0] = (a[0, 0] * b[0, 0]) + (a[0, 1] * b[1, 0]) + (a[0, 2] * b[2, 0])
  
        for (int i = 0; i < a.length; i++)
             for (int j = 0; j < a.length; j++)
                   c[i][j] = Calc(a, b, i, j);
        Print(c);
    }
    
    static void Print(int [][] arr2d) {
        for (int[] arr2d1 : arr2d) {
            for (int j = 0; j < arr2d.length; j++) {
                System.out.format("%4d", arr2d1[j]);
            }
            System.out.println();
        }
    }
    
    static int Calc(int [][] a, int [][] b, int i, int j) {
        int sum = 0;
             
        for (int x = 0; x < a.length; x++) 
             sum += a[i][x] * b[x][j];
             
        return sum;
    }
}



/*
run:
  
   1   8   5
   6   7   1
   8   7   6
 
   4   8   1
   6   5   3
   4   6   5
 
  72  78  50
  70  89  32
  98 135  59
      
*/

 



answered Feb 28, 2016 by avibootz
edited 3 days ago by avibootz
0 votes
class Program {
    public static void main(String[] args) {
                 
        int a[][] = { { 1, 8, 5 }, { 6, 7, 1 }, { 8, 7, 6 } };
        int b[][] = { { 4, 8, 1 }, { 6, 5, 3 }, { 4, 6, 5 } };
        int[][] c = new int[a.length][a.length];
  
        Print(a);
        System.out.println();    
        Print(b);
        System.out.println();
  
        // c[0, 0] = (a[0, 0] * b[0, 0]) + (a[0, 1] * b[1, 0]) + (a[0, 2] * b[2, 0])
  
        multiple_matrix(a, b, c);
         
        Print(c);
    }
    
    static void Print(int [][] arr2d) {
        for (int[] arr2d1 : arr2d) {
            for (int j = 0; j < arr2d.length; j++) {
                System.out.format("%4d", arr2d1[j]);
            }
            System.out.println();
        }
    }
    
    static void multiple_matrix(int [][] a, int [][] b, int [][] c) {
        for (int i = 0; i < c.length; i++) {
            for (int j = 0; j < c.length; j++) {
                for (int k = 0; k < a.length; k++) {
                    c[i][j] = c[i][j] + a[i][k] * b[k][j];
                }
            }
        }
    }
}



/*
run:
  
   1   8   5
   6   7   1
   8   7   6
 
   4   8   1
   6   5   3
   4   6   5
 
  72  78  50
  70  89  32
  98 135  59
      
*/

 



answered Feb 28, 2016 by avibootz
edited 3 days ago by avibootz
...