forked from Annex5061/java-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Determinant_of_Matrix.java
94 lines (82 loc) · 2.95 KB
/
Determinant_of_Matrix.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// Java program to find Determinant of a matrix
class GFG {
// Dimension of input square matrix
static final int N = 4;
// Function to get determinant of matrix
static int determinantOfMatrix(int mat[][], int n)
{
int num1, num2, det = 1, index,
total = 1; // Initialize result
// temporary array for storing row
int[] temp = new int[n + 1];
// loop for traversing the diagonal elements
for (int i = 0; i < n; i++) {
index = i; // initialize the index
// finding the index which has non zero value
while (mat[index][i] == 0 && index < n) {
index++;
}
if (index == n) // if there is non zero element
{
// the determinant of matrix as zero
continue;
}
if (index != i) {
// loop for swaping the diagonal element row
// and index row
for (int j = 0; j < n; j++) {
swap(mat, index, j, i, j);
}
// determinant sign changes when we shift
// rows go through determinant properties
det = (int)(det * Math.pow(-1, index - i));
}
// storing the values of diagonal row elements
for (int j = 0; j < n; j++) {
temp[j] = mat[i][j];
}
// traversing every row below the diagonal
// element
for (int j = i + 1; j < n; j++) {
num1 = temp[i]; // value of diagonal element
num2 = mat[j]
[i]; // value of next row element
// traversing every column of row
// and multiplying to every row
for (int k = 0; k < n; k++) {
// multiplying to make the diagonal
// element and next row element equal
mat[j][k] = (num1 * mat[j][k])
- (num2 * temp[k]);
}
total = total * num1; // Det(kA)=kDet(A);
}
}
// multiplying the diagonal elements to get
// determinant
for (int i = 0; i < n; i++) {
det = det * mat[i][i];
}
return (det / total); // Det(kA)/k=Det(A);
}
static int[][] swap(int[][] arr, int i1, int j1, int i2,
int j2)
{
int temp = arr[i1][j1];
arr[i1][j1] = arr[i2][j2];
arr[i2][j2] = temp;
return arr;
}
// Driver code
public static void main(String[] args)
{
int mat[][] = { { 1, 0, 2, -1 },
{ 3, 0, 0, 5 },
{ 2, 1, 4, -3 },
{ 1, 0, 5, 0 } };
// Function call
System.out.printf(
"Determinant of the matrix is : %d",
determinantOfMatrix(mat, N));
}
}