Matrix multiplication-matrix multiplication (Java code)

1. How to multiply between matrices-

a1 b1 c1
d1 e1 f1
a2 b2
c2 d2
e2 f2

  


The number corresponding to the first row is multiplied by the number corresponding to the first column, and the number corresponding to the first row is multiplied by the number corresponding to the second column....

finally get

a1*a2+b1*c2+c1*e2 a1*b2+b1*d2+c1*f2
d1*a2+e1*c2+f1*e2 d1*b2+e1*d2+f1*f2

Therefore, there is a rule: the rows of matrix 1 and the columns of matrix 2 are exactly the rows and columns of the new array, so it can be expressed by two for loops, and because their columns and rows are the same when multiplied and the matrix 1 The row transformation is performed only after the transformation of the columns of matrix 2 is completed. The code is as shown in the figure below:

for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++) {
                for(int k=0;k<3;k++)
                    num2[i][j]+=num[i][k]*num1[k][j];
                    System.out.print(num2[i][j]+" ");
            }
            System.out.println();
        }

topic:

Enter a two-dimensional array of 2*3 and 3*2, and find the product of the two matrices.
Input
1 2 0
3 4 2
1
3 2 4
3 1
Output
5 11
17 27
 

code:

public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[][] num = new int[2][3];
        int[][] num1=new int[3][2];
        int[][] num2=new int[2][2];
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 3; j++) {
                num[i][j] = sc.nextInt();
            }
        }
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 2; j++) {
                num1[i][j] = sc.nextInt();
            }
        }
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++) {
                for(int k=0;k<3;k++)
                    num2[i][j]+=num[i][k]*num1[k][j];
                    System.out.print(num2[i][j]+" ");
            }
            System.out.println();
        }
    }

Guess you like

Origin blog.csdn.net/zsl20200217/article/details/127086079