How to multiply two matrices (matrix) in Java

1 Answer

0 votes
public class MyClass {
    public static final int COLS1 = 3;
    public static final int COLS2 = 2;
     
    public static void main(String args[]) {
        int[][] matrix1 = {
            {4, 2, 4},
            {8, 3, 1}
        };
        int[][] matrix2 = {
            {3, 5},
            {2, 8},
            {7, 9}
        };
        int[][] mul = {
            {0, 0},
            {0, 0}
        };
 
        int rows1 = matrix1.length;
        int cols2 = matrix2[0].length;
 
        // mul[0][0] = m1[0][0] * m2[0][0] + m1[0][1] * m2[1][0] + m1[0][2] * m2[2][0] 
 
        for (int i = 0; i < rows1; i++)  {
            for (int j = 0; j < cols2; j++) {
                for (int k = 0; k < COLS1; k++) {
                    mul[i][j] += matrix1[i][k] * matrix2[k][j];
                     
                    System.out.print("mul[" + i);
                    System.out.print("][" + j);
                    System.out.print("] += m1[" + i);
                    System.out.print("][" + k);
                    System.out.print("] * m2[" + k);
                    System.out.print("][" + j + "]\n");
                }
                System.out.print("\n");
            }
        }
        for (int i = 0; i < COLS2; i++) {
            for (int j = 0; j < COLS2; j++) {
                System.out.print(mul[i][j] + " ");
            }
            System.out.print("\n");
        }
    }
}
 
 
 
/*
run:
  
mul[0][0] += m1[0][0] * m2[0][0]
mul[0][0] += m1[0][1] * m2[1][0]
mul[0][0] += m1[0][2] * m2[2][0]
 
mul[0][1] += m1[0][0] * m2[0][1]
mul[0][1] += m1[0][1] * m2[1][1]
mul[0][1] += m1[0][2] * m2[2][1]
 
mul[1][0] += m1[1][0] * m2[0][0]
mul[1][0] += m1[1][1] * m2[1][0]
mul[1][0] += m1[1][2] * m2[2][0]
 
mul[1][1] += m1[1][0] * m2[0][1]
mul[1][1] += m1[1][1] * m2[1][1]
mul[1][1] += m1[1][2] * m2[2][1]
 
44 72 
37 73 
  
*/

 



answered Sep 14, 2022 by avibootz
edited Sep 15, 2022 by avibootz

Related questions

1 answer 119 views
1 answer 129 views
1 answer 131 views
1 answer 150 views
1 answer 156 views
1 answer 161 views
...