## Friday, January 8, 2016

### Determinant of a Matrix - GeeksforGeeks

Determinant of a Matrix - GeeksforGeeks
Determinant of a Matrix is a special number that is defined only for square matrices (matrices which have same number of rows and columns). Determinant is used at many places in calculus and other matrix related algebra, it actually represents the matrix in term of a real number which can be used in solving system of linear equation and finding the inverse of a matrix.
How to calculate?
The value of determinant of a matrix can be calculated by following procedure –
For each element of first row or first column get cofactor of those elements and then multiply the element with the determinant of the corresponding cofactor, and finally add them with alternate signs. As a base case the value of determinant of a 1*1 matrix is the single value itself.
Cofactor of an element, is a matrix which we can get by removing row and column of that element from that matrix.
Determinant of 2 x 2 Matrix:
Determinant of 3 x 3 Matrix:

`// Function to get cofactor of mat[p][q] in temp[][]. n is current`
`// dimension of mat[][]`
`void` `getCofactor(``int` `mat[N][N], ``int` `temp[N][N], ``int` `p, ``int` `q, ``int` `n)`
`{`
`    ``int` `i = 0, j = 0;`
`    ``// Looping for each element of the matrix`
`    ``for` `(``int` `r = 0; r < n; r++)`
`    ``{`
`        ``for` `(``int` `c = 0; c < n; c++)`
`        ``{`
`            ``//  Copying into temporary matrix only those element`
`            ``//  which are not in given row and column`
`            ``if` `(r != p && c != q)`
`            ``{`
`                ``temp[i][j++] = mat[r]1;`
`                ``// Row is filled, so increase row index and`
`                ``// reset col index`
`                ``if` `(j == n - 1)`
`                ``{`
`                    ``j = 0;`
`                    ``i++;`
`                ``}`
`            ``}`
`        ``}`
`    ``}`
`}`
`/* Recursive function for finding determinant of matrix.`
`   ``n is current dimension of mat[][]. */`
`int` `determinantOfMatrix(``int` `mat[N][N], ``int` `n)`
`{`
`    ``int` `D = 0; ``// Initialize result`
`    ``//  Base case : if matrix contains single element`
`    ``if` `(n == 1)`
`        ``return` `mat[0][0];`
`    ``int` `temp[N][N]; ``// To store cofactors`
`    ``int` `sign = 1;  ``// To store sign multiplier`
`     ``// Iterate for each element of first row`
`    ``for` `(``int` `f = 0; f < n; f++)`
`    ``{`
`        ``// Getting Cofactor of mat[0][f]`
`        ``getCofactor(mat, temp, 0, f, n);`
`        ``D += sign * mat[0][f] * determinantOfMatrix(temp, n - 1);`
`        ``// terms are to be added with alternate sign`
`        ``sign = -sign;`
`    ``}`
`    ``return` `D;`
`}`