-
Notifications
You must be signed in to change notification settings - Fork 21.1k
Expand file tree
/
Copy pathMatrixDeterminant.java
More file actions
56 lines (47 loc) · 1.38 KB
/
MatrixDeterminant.java
File metadata and controls
56 lines (47 loc) · 1.38 KB
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
package com.thealgorithms.matrix;
// Problem: Determinant of a Matrix
// Description: Calculate the determinant of any square matrix using recursion.
// URL: https://en.wikipedia.org/wiki/Determinant
public final class MatrixDeterminant {
private MatrixDeterminant() {
// Prevent instantiation
}
public static double determinant(double[][] m) {
int n = m.length;
for (double[] row : m) {
if (row.length != n) {
throw new IllegalArgumentException("Matrix must be square");
}
}
if (n == 1) {
return m[0][0];
}
if (n == 2) {
return m[0][0] * m[1][1] - m[0][1] * m[1][0];
}
double det = 0;
for (int c = 0; c < n; c++) {
det += Math.pow(-1, c) * m[0][c] * determinant(minor(m, 0, c));
}
return det;
}
private static double[][] minor(double[][] m, int row, int col) {
int n = m.length;
double[][] min = new double[n - 1][n - 1];
int r = 0;
for (int i = 0; i < n; i++) {
if (i == row) {
continue;
}
int c = 0;
for (int j = 0; j < n; j++) {
if (j == col) {
continue;
}
min[r][c++] = m[i][j];
}
r++;
}
return min;
}
}