Page 1 of 1

Need advice on how to print a matrix in lisp

Posted: Fri Sep 20, 2013 9:24 pm
by joeish80829
… quick question.....I have a matrix defined so if i do this

(format t "~a" (get-real-2d 0 0))

it prints out the element in the first row first column

and if i do this

(format t "~a" (get-real-2d a 0 1))

it prints out the element in first row second column

and if i do this

(format t "~a" (get-real-2d a 1 0))

it prints out the element in second row first column and etc etc

the matrix a looks like this

a =
((0 1 2)
(3 4 5)
(6 7 8))

and i was hoping you can show me exactly how to write a dotimes loop or other loop that would in as few lines as possible would print out the matrix using the get-real-2d funtion so the output looks like this

0 1 2
3 4 5
6 7 8

im just hoping you can show me a slick loop that would be real small that i can use to print matrices that i can use in my lisp library something real proffessional looking...like one that would use only variables ....like

(format t "~a" (get-real-2d i j))

instead of a bunch of

(format t "~a" (get-real-2d 0 0))
(format t "~a" (get-real-2d 0 1))
(format t "~a" (get-real-2d 0 2))

etc...

Re: Need advice on how to print a matrix in lisp

Posted: Sat Sep 21, 2013 4:28 am
by Goheeca
I present a couple of solutions:

Code: Select all

(defvar *matrix* #2A((0 1 2) (3 4 5) (6 7 8)))

(format t (formatter "~&~{~{~5@A~^ ~}~^~%~}") (array-to-list *matrix*))

;;; definition of an indexer
(defun get-real-2d (matrix row col)
  (aref matrix row col))
where array-to-list is defined at stackoverflow.

Code: Select all

(defvar *matrix* #2A((0 1 2) (3 4 5) (6 7 8)))

(loop initially (fresh-line)
      for row in (array-to-list *matrix*)
      do (loop for first = 0 then 1
               for elem in row
               do (format t "~5,2,v@A" first elem))
         (terpri))
I've used various features of CL for you to wide horizons.
It's a pity that the loop keyword across iterates only over vectors and not generally over arrays and perhaps returning fresh sub-arrays (I know that it's not implemented exactly because it doesn't suit the loop approach) because multidimensional arrays are implemented for a maximal speed thus can't be composed of sub-array objects.