Wednesday, 23 November 2016

Matrix multiplication

This program show how to multiply two matrices A & B into a third matrix C. Here the matrix having 3 rows and 3 columns (3x3). As given below, inputMatrix( ) and displayMatrix( ) are two static methods which are used to read and display the matrix values respectively. java.util.Scanner class is used to read values from keyboard at runtime.



PROGRAM
import java.util.Scanner;

public class MatrixMultiplication {

 // Method to read matrix elements
 public static void inputMatrix(int temp[][]) {
  Scanner s = new Scanner(System.in);
  for(int i=0;i<3; i++) {
   for(int j=0; j<3; j++) {
    temp[i][j] = s.nextInt();
   }
  }
 }
 
 // Method to display matrix elements
 public static void displayMatrix(int temp[][]) {
  for(int i=0;i<3; i++) {
   for(int j=0; j<3; j++) {
    System.out.print(temp[i][j] + " ");
   }
   System.out.println("");
  }
 }
 
 public static void main(String[] args) {

  int a[][] = new int[3][3];  // First matrix
  int b[][] = new int[3][3];  // Second matrix
  int c[][] = new int[3][3];  // Final matrix which is to store multiplication result
  
  // Input Matrix A elements
  System.out.println("Enter the 9 numbers for first matrix (3x3)...");
  inputMatrix(a);
  
  // Input Matrix B elements
  System.out.println("Enter the 9 numbers for second matrix (3x3)...");
  inputMatrix(b);
  
  // Multiplication logic goes here
  for(int i=0; i<3; i++) {
   for(int j=0; j<3; j++) {
    for(int k=0; k<3; k++) {
     c[i][j] = c[i][j] + (a[i][k] * b[k][j]);
    }
   }
  }
  
  System.out.println("Matrix A is ...");
  displayMatrix(a);
  
  System.out.println("Matrix B is ...");
  displayMatrix(b);
  
  System.out.println("After multiplication Matrix C is ...");
  displayMatrix(c);
 }
}
OUTPUT
C:\>javac MatrixMultiplication.java
C:\>java MatrixMultiplication
Enter the 9 numbers for first matrix (3x3)...
1 2 3
4 5 6
7 8 9
Enter the 9 numbers for second matrix (3x3)...
1 2 3 
4 5 6
7 8 9
Matrix A is ...
1 2 3 
4 5 6 
7 8 9 
Matrix B is ...
1 2 3 
4 5 6 
7 8 9 
After multiplication Matrix C is ...
30 36 42 
66 81 96 
102 126 150 

No comments:

Post a Comment