thespeedracer38

Determinant Calculator for 3 by 3 matrix

Feb 5th, 2019
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.08 KB | None | 0 0
  1. /**
  2.  *
  3.  * @author Ranajoy
  4.  */
  5. public class Determinant {
  6.    
  7.     static void display(int arr[][]){
  8.         int rows = arr.length;
  9.         int cols = arr[0].length;
  10.        
  11.         for(int i = 0; i < rows; i++){
  12.             for(int j = 0; j < cols; j++){
  13.                 System.out.print(arr[i][j] + " ");
  14.             }
  15.             System.out.println("");
  16.         }
  17.         System.out.println("");
  18.     }
  19.    
  20.     static int calcDeterminant(int arr[][]){
  21.         // Expanding w.r.t first row
  22.         int det = 0;
  23.         int co_factors[][] = new int[2][2];
  24.         for(int j = 0; j < 3; j++){
  25.             // The element is arr[0][j]
  26.             // Calculating the co-factors of
  27.             // arr[0][j]
  28.             int c_i = 0;
  29.             for(int row = 1; row < 3; row++){
  30.                 int c_j = 0;
  31.                 for(int col = 0; col < 3; col++){
  32.                     // The co-factors are present in those columns to which
  33.                     // the element arr[0][j] does not belong
  34.                     if(col != j){
  35.                         co_factors[c_i][c_j] = arr[row][col];
  36.                         c_j++;
  37.                     }
  38.                 }
  39.                 c_i++;
  40.             }
  41.             System.out.println("Co-factors of " + arr[0][j] + " are");
  42.             display(co_factors);
  43.             // For even indexed columns the co-factors have a + sign
  44.             // For odd indexed columns the co-factors have a - sign
  45.             if(j % 2 == 0){
  46.                 det += arr[0][j] * ((co_factors[0][0] * co_factors[1][1]) -
  47.                         ((co_factors[0][1] * co_factors[1][0])));
  48.             }
  49.             else{
  50.                 det -= arr[0][j] * ((co_factors[0][0] * co_factors[1][1]) -
  51.                         ((co_factors[0][1] * co_factors[1][0])));
  52.             }
  53.         }
  54.         return det;
  55.     }
  56.    
  57.     public static void main(String[] args) {
  58.         int arr[][] = {
  59.             {1, 2, 3},
  60.             {1, 1, 1},
  61.             {1, 2, 3}
  62.         };
  63.         System.out.println("Determinant = " + calcDeterminant(arr));
  64.     }
  65. }
Add Comment
Please, Sign In to add comment