Skip to content

Instantly share code, notes, and snippets.

@NivenT
Last active November 4, 2016 00:32
Show Gist options
  • Save NivenT/7cff47b4ddd3bb33f98e762dd7e6b50c to your computer and use it in GitHub Desktop.
Save NivenT/7cff47b4ddd3bb33f98e762dd7e6b50c to your computer and use it in GitHub Desktop.
Had to find the determinant of a 5x5 matrix using row reduction, and show my steps as part of a homework problem, so I put together some code to do it for me and generate the latex I need while it's at it.
(defun range (max &key (min 0) (step 1) (runninglist nil))
(if (<= max min) runninglist (range max :min (+ min step) :step step :runninglist (append runninglist `(,min)))))
(defun entry (mat i j)
(elt (elt mat i) j))(defun row->latex (row)
(format t "~a ~{& ~a ~}\\\\~%" (car row) (cdr row))
)
(defun mat->latex (mat)
(princ "\\begin{vmatrix}")
(princ #\newline)
(loop for row in mat do (row->latex row))
(princ "\\end{vmatrix}")
(princ #\newline)
)
(defun elim-col (mat col d)
(let ((eliminated mat) (rows (range (length mat))) (cols (range (length (car mat)))))
(setf d (* d (entry mat col col)))
(setf (elt eliminated col)
(mapcar #'(lambda (x) (/ x (entry mat col col))) (elt eliminated col))
)
(unless (= d 1)
(princ #\=)
(princ (write-to-string d))
(princ #\newline)
(mat->latex eliminated)
)
(loop for row in rows do (unless (= row col)
;(let ((not-print? (= 0 (entry eliminated row col))))
(setf (elt eliminated row)
(mapcar #'(lambda (c) (- (entry eliminated row c)
(* (entry eliminated row col)
(entry eliminated col c))))
cols)
)
; Probably more verbose than need be
;(unless not-print?
; (princ #\=)
; (unless (= d 1)
; (princ (write-to-string d)))
; (princ #\newline)
; (mat->latex eliminated)
;)
;)
))
(princ #\=)
(unless (= d 1) (princ (write-to-string d)))
(princ #\newline)
(mat->latex eliminated)
(list eliminated d)
)
)
(defun det (mat)
(mat->latex mat)
(let ((reduced (list mat 1)) (cols (range (length (car mat)))))
(loop for col in cols do
(setf reduced (elim-col (car reduced) col (cadr reduced)))
)
(princ #\=)
(princ (write-to-string (cadr reduced)))
(cadr reduced)
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment