Wednesday, November 14, 2012

Programming in R, computing determinant of matrix.


Assume that the matrix is square with number of rows greater than or equal to 2.
The determinant of the 2 by 2 matrix


$
A = \begin{array}{ll}
a_{11} & a_{12}\\
a_{21} & a_{22} \\
\end{array}
$

is given by A[1,1]* A[2,2] - A[2,1] * A[1,2]. To be continued.....

$\sum_{\forall j} A[1,j] * (-1) ^ {j+1} *det(A[-1,-j]$

where A[-1, -j] denotes the submatrix obtained by deleting the first row and the jth column! R has a clever method of denoting the row or column to be deleted.


here is a simple recursive implementation with debugging statements. We ask the reader to remove them and simplify the code.

"""
# file    mydet.R
# author  your name here!


mydet <- function (A) {
    rows <-nrow(A)
    print (c("rows=", rows))
    if (rows != ncol(A)) {
       print("A is not a square matrix!!!")
    }
    if (rows == 2) {
       result <- (A[1,1] * A[2,2] - A[2,1] * A[1,2])
       print (c("result=", result))
       return(result)
    }

    # expand by first row.
    tot = 0.0
    sign = 1
    for (j in seq(1, rows)){
       tot  = tot + sign * A[1,j] * mydet(A[-1,-j])
       sign = -sign
    }
    return(tot)
}