/* Recursive definition of determinate using expansion by minors.*/
#define NULL 0
double Determinant(double **a,int n)
{
int i,j,j1,j2 ; // general loop and matrix subscripts
double det = 0 ; // init determinant
double **m = NULL ; // pointer to pointers to implement 2D square array
if (n < 1) // error condition, should never get here
{
error("Number of Rows and Columns is less than 1");
}
else if (n == 1)
{ // should not get here
det = a[0][0] ;
}
else if (n == 2) // basic 2X2 sub-matrix determinate definition.
{ // When n==2, this ends the the recursion series
det = a[0][0] * a[1][1] - a[1][0] * a[0][1];
}
else // recursion continues, solve next sub-matrix
{ // solve the next minor by building a
// sub matrix
det = 0 ; // initialize determinant of sub-matrix
// for each column in sub-matrix
for (j1 = 0 ; j1 < n ; j1++)
{
// get space for the pointer list
m
= (double **) malloc((n
-1)* sizeof(double *)) ;
for (i = 0 ; i < n-1 ; i++)
m
[i
] = (double*) malloc((n
-1)* sizeof(double)) ;// i[0][1][2][3] first malloc
// m -> + + + + space for 4 pointers
// | | | | j second malloc
// | | | +-> _ _ _ [0] pointers to
// | | +----> _ _ _ [1] and memory for
// | +-------> _ a _ [2] 4 doubles
// +----------> _ _ _ [3]
//
// a[1][2]
// build sub-matrix with minor elements excluded
for (i = 1 ; i < n ; i++)
{
j2 = 0 ; // start at first sum-matrix column position
// loop to copy source matrix less one column
for (j = 0 ; j < n ; j++)
{
if (j == j1)
continue ; // don't copy the minor column element
m[i-1][j2] = a[i][j] ; // copy source element into new sub-matrix
// i-1 because new sub-matrix is one row
// (and column) smaller with excluded minors
j2++ ; // move to next sub-matrix column position
}
}
det
+= (double)pow(-1.0,1.0 + j1
+ 1.0) * a
[0][j1
] * Determinant
(m
,n
-1) ;// sum x raised to y power
// recursively get determinant of next
// sub-matrix which is now one
// row & column smaller
for (i = 0 ; i < n-1 ; i++) // free the storage allocated to
free(m
[i
]) ; // to this minor's set of pointers free(m
) ; // free the storage for the original } // pointer to pointer
}
return(det) ;
}