I am writing a method that will calculate the determinant of a matrix (here, a two-dimensional array) containing doubles. Here is what I've written:
/// <summary>
/// Checks to see if a matrix is square, and then computes its determinant
/// </summary>
/// <returns></returns>
public double Determinant()
{
// Check to make sure the matrix is square. Only square matrices
// have determinants.
if (!this.isSquare())
{
throw new Exception("The matrix does not have a determinant");
}
// Check to see if the matrix has dimensions 1x1.
// The determinant of a 1x1 matrix is equal to the value stored at (0,0).
if (this.NumberOfRows == 1)
{
return this.GetElement(0, 0);
}
double determinant = 0;
// Loop through the top row of the matrix.
for (int columnIndex = 0; columnIndex < this.NumberOfColumns; columnIndex++)
{
Matrix cofactor = new Matrix(this.NumberOfRows - 1, this.NumberOfColumns - 1);
//fill cofactor
//I dont Know what to do here?
determinant += this.GetElement(1, columnIndex) * cofactor.Determinant();
}
return determinant;
}
What I am missing is what should go at the line fill cofactor
.
Can someone suggest what I should do there? Basically, what is the best way to add elements to cofactor from the original matrix while ignoring those that appear in the row or column of my current location in the matrix?