Created
February 4, 2014 16:11
-
-
Save sqeezy/8806746 to your computer and use it in GitHub Desktop.
Compute the determinant of a matrix.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Duplicates a ComplexMatrix without one columns and one row | |
/// </summary> | |
/// <param name="matrix"></param> | |
/// <param name="column"></param> | |
/// <param name="row"></param> | |
/// <returns></returns> | |
private Matrix make_matrix(Matrix matrix, int column) | |
{ | |
Matrix new_matrix = new Matrix(matrix.Rows - 1, matrix.Columns - 1); | |
///2 Parts | |
//1st | |
for (int y = 0; y < column; y++) | |
{ | |
for (int x = 1; x < matrix.Rows; x++) | |
{ | |
new_matrix[(x - 1), y] = matrix[x, y]; | |
} | |
} | |
//2nd | |
for (int y = (column + 1); y < matrix.Columns; y++) | |
{ | |
for (int x = 1; x < matrix.Rows; x++) | |
{ | |
new_matrix[(x - 1), (y - 1)] = matrix[x, y]; | |
} | |
} | |
return new_matrix; | |
} | |
//If the matrix is bigger then 2x2, det will be cast recursive until it is. | |
private double det(Matrix matrix) | |
{ | |
if (matrix.Rows != matrix.Columns) | |
{ | |
throw new Exception("Determinants can only be computed from square matrices."); | |
} | |
if (matrix.Rows == 2 && matrix.Columns == 2) | |
{ | |
return ((matrix[0, 0] * matrix[1, 1]) - (matrix[0, 1] * matrix[1, 0])); | |
} | |
//ComplexMatrix is bigger then 2x2 | |
double ret_det = 0; | |
bool negative = false; | |
for (int i = 0; i < matrix.Columns; i++) | |
{ | |
Matrix smallMatrix = make_matrix(matrix, i); | |
if (negative) | |
{ | |
ret_det += (-1) * matrix[0, i] * det(smallMatrix); | |
negative = false; | |
} | |
else | |
{ | |
ret_det += matrix[0, i] * det(smallMatrix); | |
negative = true; | |
} | |
} | |
return ret_det; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment