thespeedracer38

Determinant Calculator for n by n matrix

Feb 7th, 2019
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.82 KB | None | 0 0
  1. static int findDeterminant(int arr[][]){
  2.         int rows = arr.length;
  3.         int cols = arr[0].length;
  4.         // Base Condition
  5.         if(rows == 2 && cols == 2){
  6.             // We stop when rows = 2, and cols = 2
  7.             // because to calculate the
  8.             // determinant of a 2 by 2 matrix
  9.             // it does not need to be broken further
  10.             int det = (arr[0][0] * arr[1][1]) - (arr[0][1] * arr[1][0]);
  11.             return det;
  12.         }
  13.         else{
  14.             int det = 0;
  15.             int co_factors[][] = new int[rows - 1][cols - 1];
  16.             for(int j = 0; j < cols; j++){
  17.                 // The element is arr[0][j]
  18.                 // Calculating the co-factors of
  19.                 // arr[0][j]
  20.                 int c_i = 0;
  21.                 for(int row = 1; row < cols; row++){
  22.                     int c_j = 0;
  23.                     for(int col = 0; col < cols; col++){
  24.                         // The co-factors are present in those columns to which
  25.                         // the element arr[0][j] does not belong
  26.                         if(col != j){
  27.                             co_factors[c_i][c_j] = arr[row][col];
  28.                             c_j++;
  29.                         }
  30.                     }
  31.                     c_i++;
  32.                 }
  33.                 System.out.println("Co-factors of " + arr[0][j] + " are");
  34.                 display(co_factors);
  35.                 // For even indexed columns the co-factors have a + sign
  36.                 // For odd indexed columns the co-factors have a - sign
  37.                 if(j % 2 == 0){
  38.                     det += arr[0][j] * findDeterminant(co_factors);
  39.                 }
  40.                 else{
  41.                     det -= arr[0][j] * findDeterminant(co_factors);
  42.                 }
  43.             }
  44.             return det;
  45.         }
  46.     }
Add Comment
Please, Sign In to add comment