Multiplying Two Matrices in Java

Problem:

Write a program to multiply two matrices.


Output:

Enter matrix1: 5 3 9 0 6 5 2 3 5
Enter matrix2: 0 4 2 9 5 3 1 0 5
5.0 3.0 9.0     0.0 4.0 2.0     36.0 35.0 64.0
0.0 6.0 5.0  x  9.0 5.0 3.0  =  59.0 30.0 43.0
2.0 3.0 5.0     1.0 0.0 5.0     32.0 23.0 38.0


Solution:

 import java.util.Scanner;

public class MultiplyMatricies
{
  public static double[][] multiplyMatrix(double[][] a, double[][] b)
  {
    double[][] c = new double[3][3];
    for (int i =0;i<c.length;i++)
    {
      for (int j =0;j<c[i].length;j++)
      {
        c[i][j] = a[i][0]*b[0][j] + 
              a[i][1]*b[1][j] + 
              a[i][2]*b[2][j];
      }
    }
    return c;
  }
  public static double[][] scanA()
  {
  System.out.print("Enter matrix1: ");
  Scanner scan = new Scanner (System.in);
  double[][] a = new double[3][3];
  for (int i =0;i<a.length;i++)
  {
    for (int j =0;j<a[i].length;j++)
    {
      a[i][j]= scan.nextInt();
    }
  }
    return a;
  }
  
  public static double[][] scanB()
  {
    System.out.print("Enter matrix2: ");
  Scanner scan = new Scanner (System.in);
  double[][] b = new double[3][3];
  for (int i =0;i<b.length;i++)
  {
    for (int j =0;j<b[i].length;j++)
    {
      b[i][j]= scan.nextInt();
    }
  }
    return b;
  }
  
  public static void printMatrix(double[][] a,double[][] b, double[][] c)
  {
    for (int i =0; i< a.length;i++)
    {
      for (int j =0;j< a[i].length;j++)
      {
        System.out.print(a[i][j] + " ");
      }
      if ( i ==1)
      System.out.print("  x  ");
      else 
      System.out.print("     ");
      for (int j =0;j< b[i].length;j++)
      {
        System.out.print(b[i][j] + " ");
      }
      if ( i ==1)
      System.out.print("  =  ");
      else 
      System.out.print("     ");
      for (int j =0;j< c[i].length;j++)
      {
        System.out.print(c[i][j] + " ");
      }
      
      System.out.println();
    }
  }
  
  public static void main (String[] args)
  {
    
    double[][] a= scanA();
    double[][] b= scanB();
    double[][] c = multiplyMatrix(a,b);
    printMatrix(a,b,c);
  }
}

No comments:

Post a Comment