det method
Calculates the determinant of the matrix.
Throws MatrixInvalidDimensions if matrix is not square and at least a 2x2
Implementation
double det() {
if (this.m != this.n) {
throw new MatrixInvalidDimensions();
}
if (this.m < 2) {
throw new MatrixInvalidDimensions();
}
if (this.m == 2) {
return _values[0][0] * _values[1][1] - _values[1][0] * _values[0][1];
}
// should really pick a row or column with a lot of zeros.
int bestColumnCount = 0;
int bestColumn = -1;
for (int c = 0; c < this.n; c++) {
int count = 0;
for (int r = 0; r < this.m; r++) {
if (_values[r][c] == 0.0) {
count++;
}
}
if (count >= bestColumnCount) {
bestColumnCount = count;
bestColumn = c;
}
}
int bestRowCount = 0;
int bestRow = -1;
for (int r = 0; r < this.m; r++) {
int count = 0;
for (int c = 0; c < this.n; c++) {
if (_values[r][c] == 0.0) {
count++;
}
}
if (count >= bestRowCount) {
bestRowCount = count;
bestRow = r;
}
}
if (bestColumnCount > bestRowCount) {
double det = 0.0;
int c = bestColumn;
for (int r = 0; r < this.m; r++) {
double v = this[r][c];
if (v != 0.0) {
Matrix sub = cut(r, c);
double coFactor = pow(-1, r + c) * sub.det();
det += v * coFactor;
}
}
return det;
} else {
double det = 0.0;
int r = bestRow;
for (int c = 0; c < this.n; c++) {
double v = this[r][c];
if (v != 0.0) {
Matrix sub = cut(r, c);
double coFactor = pow(-1, r + c) * sub.det();
det += v * coFactor;
}
}
return det;
}
}