Search code examples
carraysdeterminantsdimensional

how to find determinant


double Determinant(double *X, int N){

    /*Solution*/

} 

int main(void)
{

  double X[] = {3, 1, 2, 
                7, 9, 2, 
                4, 6, 9};

  if (Determinant(X,3) == 164) 
   {
    printf("✓");   
   } 

 }

how to find one dimensional array NxN determinant matrix? Can someone help me? thanks in advance.


Solution

  • A determinant is commonly computed in a recursive form for N > 2 as SUM(ai0 * det(Xi * (-1)i) where Xi is the sub-matrix obtained by removing the first column and the i-th line. In C language, it can be written as:

    double Determinant(double *X, int N) {
        if (N == 2) {                         // trivial for a 2-2 matrix
            return X[0] * X[3] - X[1] * X[2];
        }
        // allocate a sequential array for the sub-matrix
        double *Y = malloc((N - 1) * (N - 1) * sizeof(double));
        // recursively compute the determinant
        double det = 0.;
        for (int k = 0, s = 1; k < N; k++) {
            // build the submatrix
            for (int i = 0, l=0; i < N; i++) {
                if (i == k) continue;
                for (int j = 1; j < N; j++) {
                    Y[l++] = X[j + i * N];
                }
            }
            det += X[k * N] * Determinant(Y, N - 1) * s;
            s = -s;
        }
        free(Y);                        // do not forget to de-alloc...
        return det;
    }