Java中的矩阵乘法

时间:2020-02-23 14:35:26  来源:igfitidea点击:

在本教程中,我们将看到如何将两个矩阵乘以Java。

import java.util.Scanner;
 
public class MatrixOperator
{
   public static void main(String args[])
   {
   
      int r1, c1, r2, c2, sum = 0, i, j, k;
      Scanner in = new Scanner(System.in);
      
      System.out.print("Enter number of rows and columns of first matrix : ");
      r1 = in.nextInt();
      c1 = in.nextInt();
      
      int first[][] = new int[r1][c1];
      
      System.out.print("Enter first matrix elements : ");
      
      for(i=0 ; i<r1; i++){
         for(j=0; j<c1; j++){
            first[i][j] = in.nextInt();
         }
      }
 
      System.out.print("Enter number of rows and columns of second matrix :");
      r2 = in.nextInt();
      c2 = in.nextInt();
 
      if ( c1 != r2 ){
         System.out.print("Matrix of the entered order can't be Multiplied..!!");
      }
      else{
         int second[][] = new int[r2][c2];
         int multiply[][] = new int[r1][c2];
 
         System.out.print("Enter second matrix elements : \n");
 
         for(i=0; i<r2; i++){
            for(j=0; j<c2; j++){
               second[i][j] = in.nextInt();
            }
        }
 
         for(i=0; i<r1; i++){
            for(j=0; j<c2; j++){   
               for(k=0; k<r2; k++){
                  sum = sum + first[i][k]*second[k][j];
               }
               multiply[i][j] = sum;
               sum = 0;
            }
         }
 
         System.out.print("Matrix multiplication result is : ");
 
         for(i=0; i<r1; i++){
            for(j=0; j<c2; j++){
               System.out.print(multiply[i][j] + "\t");
            }
            System.out.print("\n");
         }
      }
	  
   }
}

输出:

Enter number of rows and columns of first matrix : 2 2
Enter first matrix elements : 2 4 6 8
Enter number of rows and columns of second matrix :2 2
Enter second matrix elements : 3 6 9 12
Matrix multiplication result is :
42 60
90 132