Last active
December 27, 2019 14:06
-
-
Save chebert/f6c96f7c3edfd45c27ce6bd7a4587dff to your computer and use it in GitHub Desktop.
Example of How Matrices could be implemented using Vectors In Lisp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defun make-vector (length elt) (make-array length :initial-element elt)) | |
(defun vector-elt (vec i) (aref vec i)) | |
(defun vector-set! (vec i elt) (setf (aref vec i) elt)) | |
(defun matrix (m n vec) (list m n vec)) | |
(defun matrix-m (m) (first m)) | |
(defun matrix-n (m) (second m)) | |
(defun matrix-vec (m) (third m)) | |
(defun num-elements (m n) | |
(* m n)) | |
(num-elements 3 2) | |
;; => 6 | |
(defun matrix-zero (m n) | |
(matrix m n (make-vector (num-elements m n) 0))) | |
(matrix-zero 3 1) | |
;; => (3 1 #(0 0 0)) | |
(defparameter *mat* (matrix 2 2 #(0 1 | |
2 3))) | |
;; => *MAT* | |
(defun matrix-vec-idx (mat i j) | |
(+ (* i (matrix-n mat)) j)) | |
(matrix-vec-idx *mat* 1 0) | |
;; => 2 | |
(defun matrix-elt (mat i j) | |
(vector-elt (matrix-vec mat) (matrix-vec-idx mat i j))) | |
(matrix-elt *mat* 1 0) | |
;; => 2 | |
(matrix-elt *mat* 0 1) | |
;; => 1 | |
(defparameter *mat2* (matrix 3 3 #(0 1 2 | |
3 4 5 | |
6 7 8))) | |
(defun matrix-sub-matrix (mat i j m n) | |
(let* ((vec (make-vector (num-elements m n) 0)) | |
(mat-res (matrix m n vec))) | |
(dotimes (r m) | |
(dotimes (c n) | |
(vector-set! vec | |
(matrix-vec-idx mat-res r c) | |
(matrix-elt mat (+ i r) (+ c j))))) | |
mat-res)) | |
(matrix-sub-matrix *mat2* 0 0 1 1) | |
;; => (1 1 #(0)) | |
(matrix-sub-matrix *mat2* 0 0 2 2) | |
;; => (2 2 #(0 1 | |
;; 3 4)) | |
(matrix-sub-matrix *mat2* 0 0 3 3) | |
;; => (3 3 #(0 1 2 | |
;; 3 4 5 | |
;; 6 7 8)) | |
(matrix-sub-matrix *mat2* 2 0 1 3) | |
;; => (1 3 #(6 7 8)) | |
(defun matrix-row (mat i) | |
(matrix-sub-matrix mat i 0 1 (matrix-n mat))) | |
*mat* | |
;; => (2 2 #(0 1 | |
;; 2 3)) | |
(matrix-row *mat* 0) | |
;; => (1 2 #(0 1)) | |
(matrix-row *mat* 1) | |
;; => (1 2 #(1 2)) | |
(defun matrix-col (mat j) | |
(matrix-sub-matrix mat 0 j (matrix-m mat) 1)) | |
*mat* | |
;; => (2 2 #(0 1 | |
;; 2 3)) | |
(matrix-col *mat* 0) | |
;; => (2 1 #(0 2)) | |
(matrix-col *mat* 1) | |
;; => (2 1 #(1 3)) | |
(defun matrix-print (mat &optional (stream t)) | |
(dotimes (i (matrix-m mat)) | |
(format stream "~&[ ") | |
(dotimes (j (matrix-n mat)) | |
(format stream "~A " (matrix-elt mat i j))) | |
(format stream "]~%")) | |
mat) | |
(matrix-print *mat*) | |
#|| | |
Output: | |
[ 0 1 ] | |
[ 2 3 ] | |
||# | |
;; => (2 2 #(0 1 2 3)) | |
(matrix-print (matrix-col *mat2* 2)) | |
#|| | |
Output: | |
[ 2 ] | |
[ 5 ] | |
[ 8 ] | |
||# | |
;; => (3 1 #(2 5 8)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment