Matrices (we need to write these functions)
;; creates a matrix - a vector of vectors, each row of the matrix is a vector
(define (make-matrix rows columns)
(do ((m (make-vector rows))
(i 0 (+ i 1)))
((= i rows) m)
(vector-set! m i (make-vector columns))))
;; returns a vector of length n filled with
;; random numbers from 0..m
(define (makeNVector n m)
(let* ((v (make-vector n)))
(do ((i 0 (+ i 1)))
((= i n) v)
(vector-set! v i (random m)))))
;; creates a matrix - a vector of vectors, each row of the matrix is a vector
;; with random values up to rannumber
(define (makeNmatrix rows columns rannumber)
(do ((m (make-vector rows))
(i 0 (+ i 1)))
((= i rows) m)
(vector-set! m i (makeNVector columns rannumber))))
;; checks to see if the argument is a matrix
(define (matrix? x)
(and (vector? x)
(> (vector-length x) 0)
(vector? (vector-ref x 0))))
;;find the length of the rows and columns:
(define (matrix-rows x)
(vector-length x))
(define (matrix-columns x)
(vector-length (vector-ref x 0)))
;; return the value at the position i,j
(define (matrix-ref m i j)
(vector-ref (vector-ref m i) j))
;; set the value of the matrix at postion i,j
(define (matrix-set! m i j x)
(vector-set! (vector-ref m i) j x))
;; Write a vector of length n to a file named fname.
;; The first line of the file has the length of the vector
;; This version generates random numbers from 0..99
(define (write-vector-file fname n)
(let ((p (open-output-file fname)))
(write n p)
(newline p)
(do ((i 0 (+ i 1)))
((>= i n) (close-output-port p))
(write (random 100) p) (write-char #\ p))))
;; Write a matrix with dimensions rows x cols to a file named fname.
;; The first line of the file has the values of rows and cols
;; This version generates random numbers from 0..99
(define (write-matrix-file fname rows cols)
(let ((p (open-output-file fname)))
(write rows p)
(write-char #\ p) ;; write a space character
(write cols p)
(newline p)
(do ((i 0 (+ i 1)))
((>= i rows) (close-output-port p))
(do ((j 0 (+ j 1)))
((>= j cols))
(write (random 100) p) (write-char #\ p))
(newline p))))
;; Read a vector of numbers from a file with name fname.
;; The first line of the file is the length of the vector
(define (read-vector-file fname)
(let* ((p (open-input-file fname))
(i 0)
(n (read p))
(v (make-vector n)))
(do ((x (read p) (read p)))
((eof-object? x)
(begin
(close-input-port p)
;; (write "Closing file")
;; (newline)
;; (write "V=")
;; (write v)
v))
(vector-set! v i x)
;; (write v) (newline)
(set! i (+ i 1)))))
;; Read a matrix from a file. The first line has nrows and ncols.
(define (read-matrix-file fname)
(let* ((p (open-input-file fname))
(nrows (read p))
(ncols (read p))
(row 0)
(col 0)
(m (make-matrix nrows ncols)))
(do ((x (read p) (read p)))
((or (eof-object? x) (= row nrows))
(begin
(close-input-port p)
m))
(matrix-set! m row col x)
(set! col (+ col 1))
(if (= col ncols)
(begin
(set! col 0)
(set! row (+ row 1)))))))