## Matrix Determinant And Inverse

### May 23, 2017

We begin with a function that, given a matrix *A* and a cell at location *A _{ij}* in the matrix, returns a newly-allocated matrix from which row

*i*and column

*j*have been deleted:

(define (sub-matrix a i j) (let ((r (matrix-rows a)) (c (matrix-cols a))) (let ((m (make-matrix (- r 1) (- c 1))) (new-i -1)) (for (old-i c) (when (not (= old-i i)) (set! new-i (+ new-i 1)) (let ((new-j -1)) (for (old-j r) (when (not (= old-j j)) (set! new-j (+ new-j 1)) (matrix-set! m new-i new-j (matrix-ref a old-i old-j))))))) m)))

That function doesn’t require *A* to be square, but the remaining functions do. Here we calculate the determinant by taking the first row of the matrix; the calculation is recursive, with a 2 × 2 matrix being the base case:

(define (matrix-determinant a) ; assume a is square (let ((n (matrix-rows a))) (if (= n 2) (- (* (matrix-ref a 0 0) (matrix-ref a 1 1)) (* (matrix-ref a 1 0) (matrix-ref a 0 1))) (let loop ((j 0) (k 1) (d 0)) (if (= j n) d (loop (+ j 1) (* k -1) (+ d (* k (matrix-ref a 0 j) (matrix-determinant (sub-matrix a 0 j))))))))))

The matrix of cofactors replaces each cell in a matrix with the determinant of the sub-matrix that eliminates the cell:

(define (matrix-cofactors a) ; assume a is square (let* ((n (matrix-rows a)) (cof (make-matrix n n))) (if (= n 2) (for (i n) (for (j n) (matrix-set! cof i j (* (expt -1 (+ i j)) (matrix-ref a (- 1 i) (- 1 j)))))) (for (i n) (for (j n) (matrix-set! cof i j (* (expt -1 (+ i j)) (matrix-determinant (sub-matrix a i j))))))) cof))

The adjugate is the transpose of the cofactor matrix:

(define (matrix-adjugate a) (matrix-transpose (matrix-cofactors a)))

Finally, the inverse is the scalar product of the inverse of the determinant times the adjugate:

(define (matrix-inverse a) (matrix-scalar-multiply (/ (matrix-determinant a)) (matrix-adjugate a)))

Who makes up all these words? Here’s an example showing that the product of a matrix and its inverse is the identity matrix:

> (define a '#( #(6 24 1) #(13 16 10) #(20 17 15))) > (matrix-multiply a (matrix-inverse a)) #(#(1 0 0) #(0 1 0) #(0 0 1))

We used the matrix datatype from the Standard Prelude and basic arithmetic on matrices from a previous exercise. You can run the program at http://ideone.com/nZGfo3.

Pages: 1 2

No worse than

addend, summand, subtrahend, minuend, multiplicand.In Python, the determinant part.

I’ve found these two links with explanations and code. It’s quite a hassle for larger dimensions….

Inverse of a matrix: http://www.geeksforgeeks.org/adjoint-inverse-matrix/

Determinant of a matrix: http://www.geeksforgeeks.org/determinant-of-a-matrix/

Though, I haven’t tried their code yet.

Here in Python an implementation of an LU decomposition. Once the matrix is decomposed, the determinant and inverse are straightforward.

Klong (for determinant)