Industrial Training




Calculating Determinant



Suppose we want to find out determinant value of a n x n matrix. Once the order of the determinant is supplied to the scanf( ) function, memory required to accommodate the matrix is allocated using the function calloc( ). Into this allocated memory then the matrix whose determinant value is to be obtained is received through the keyboard.

Suppose you wish to find the determinant value of a 4 by 4 matrix. Then each element in the first row of this matrix is to be multiplied with a suitable 3 by 3 determinant. But while evaluating a 3 by 3 determinant we again need to multiply the elements of first row of the 3 by 3 determinant by an appropriate 2 by 2 determinant. That's where recursion comes in. To make things further difficult the sign (+/-) should change for every alternate element. The logic used here is: to evaluate a n x n determinant we multiply the first row elements of this determinant with a corresponding n-1 x n-1 determinant by first copying the n-1 x n-1 determinant into pre-allocated memory. We continue this process recursively till we reach a 1 x 1 determinant and then retrace back the steps.

#include "stdlib.h"

#include "alloc.h"

main( )

{

int *arr, sum, n, i, j, pos, num ;

printf ( "\nEnter value of n for ( n x n ) matrix " ) ;

scanf ( "%d", &n ) ;

/* allocate memory to accomodate the determinant */

arr = calloc ( n * n, 2 ) ;

printf ( "\nEnter numbers :\n" ) ;

for ( i = 0 ; i < n ; i++ )

{

for ( j = 0 ; j < n ; j++ )

{

scanf ( "%d", &num ) ;

pos = i * n + j ;

arr[pos] = num ;

}

}

sum = detmat ( arr, n ) ;

free ( arr ) ;

printf ( "\n%d", sum ) ;

}

detmat ( int *arr, int order )

{

int sign = 1, sum = 0, i, j, k, count, *arr2 ;

int newsize, newpos, pos ;

if ( order == 1 )

return ( arr[0] ) ;

for ( i = 0 ; i < order ; i++, sign *= -1 )

{

/* copy n-1 by n-1 array into another array */

newsize = ( order - 1 ) * ( order - 1 ) ;

arr2 = calloc ( newsize, 2 ) ;

for ( j = 1 ; j < order ; j++ )

{

for ( k = 0, count = 0 ; k < order ; k++ )

{

if ( k == i )

continue ;

pos = j * order + k ;

newpos = ( j - 1 ) * ( order - 1 ) + count ;

arr2[newpos] = arr[pos] ;

count++ ;

}

}

/* find determinant value of n-1 by n-1 array and addit to sum */

sum = sum + arr[i] * sign * detmat ( arr2, order - 1 ) ;

free ( arr2 ) ;

}

return ( sum ) ;

}



Hi I am Pluto.