Skip to content

Instantly share code, notes, and snippets.

@oranenj
Created February 4, 2009 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oranenj/58093 to your computer and use it in GitHub Desktop.
Save oranenj/58093 to your computer and use it in GitHub Desktop.
(defn col-seq [m col]
(for [i (range (count m))] (get-in m [i col])))
(defn row-seq [m row]
(seq (m row)))
(defn rows [m]
(for [r (range (count m))] (row-seq m r)))
(defn cols [m]
(for [c (range (count (m 0)))] (col-seq m c)))
(defn vectorify
"takes a sequence and splits it into a matrix of the given width"
[m-seq row-width]
(vec (map vec (partition row-width m-seq))))
(defn dot-product
"takes two vectors, that is, sequences of numbers of equal length"
[v1 v2]
(reduce + 0 (map * v1 v2)))
(defn matrix-multiply [m1 m2]
(let [res (for [r (rows m1)
c (cols m2)]
(dot-product r c))]
; the row-width of the second matrix dictates the row-width of the result
(vectorify res (count (m2 0)))))
(def a [[1 2]
[3 4]])
(def b [[5 6]
[7 8]])
(matrix-multiply a b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment