矩阵乘法Java程序

时间:2020-01-09 10:35:34  来源:igfitidea点击:

这篇文章展示了一个将两个矩阵相乘的Java程序。

要将一个矩阵与另一个矩阵相乘,我们需要对行和列进行点积运算。

矩阵乘法的Java程序

在矩阵乘法Java程序中,最初会提示用户输入矩阵。我们还可以检查第一个矩阵中的列数是否等于第二个矩阵中的行数。然后,使用这两个矩阵即可进行乘法运算。

import java.util.Scanner;

public class MatrixMultiplication {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("Enter number of rows and columns in the matrix : ");
    int r1 = in.nextInt();
    int c1 = in.nextInt();
    // First matrix
    int[][] matrix1 = prepareMatrix(r1, c1);
    System.out.print("Enter number of rows and columns in the matrix : ");
    int r2 = in.nextInt();
    int c2 = in.nextInt();
		
    if(c1 != r2){
      in.close();
      throw new IllegalArgumentException("Number of columns in the first matrix should be equal to the number of rows in the second matrix");
    }
    // Second matrix
    int[][] matrix2 = prepareMatrix(r2, c2);
    // multiplied result stored in this matrix
    int multiplyMatrix[][] = new int[r1][c2];
    int sum = 0;
    for(int i = 0; i < r1; i++){
      for(int j = 0; j < c2; j++){                
        for(int k = 0; k < c1; k++){
          sum = sum + matrix1[i][k] * matrix2[k][j];
        }
        multiplyMatrix[i][j] = sum;
        sum = 0;
      }
    }        
		
    System.out.println("Multiplied Matrix : " );
    for(int i = 0; i < r1; i++){
      for(int j = 0; j < c2; j++){
        System.out.print(" " +multiplyMatrix[i][j]+"\t");
      }
      System.out.println();
    }
    if(in != null){
      in.close();
    }
  }

  private static int[][] prepareMatrix(int row, int column){
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter elements of Matrix : ");
    int matrix[][] = new int[row][column];
    for(int i = 0; i < row; i++){
      for(int j = 0; j < column; j++){
        matrix[i][j] = sc.nextInt();
      }
    }
    System.out.println("Entered Matrix : " );
    for(int i = 0; i < row; i++){
      for(int j = 0; j < column; j++){
        System.out.print(" " +matrix[i][j]+"\t");
      }
      System.out.println();
    }
    return matrix;
  }
}

输出:

Enter number of rows and columns in the matrix : 3 3
Enter elements of Matrix : 1 3 5 7 9 11 13 15 17
Entered Matrix : 
 1	 3	 5	
 7	 9	 11	
 13	 15	 17	
Enter number of rows and columns in the matrix : 3 3
Enter elements of Matrix : 2 4 6 8 10 12 14 16 18
Entered Matrix : 
 2	 4	 6	
 8	 10	 12	
 14	 16	 18	
Multiplied Matrix : 
 96	 114	 132	
 240	 294	 348	
 384	 474	 564