timing matrix multiplication
(defn feature-vec [n] | |
(map (partial cons 1) | |
(for [x (range n)] | |
(take 22 (repeatedly rand))))) | |
(defn dot-product [x y] | |
(reduce + (map * x y))) | |
(defn transpose | |
"returns the transposition of a `coll` of vectors" | |
[coll] | |
(apply map vector coll)) | |
(defn matrix-mult | |
[mat1 mat2] | |
(let [row-mult (fn [mat row] | |
(map (partial dot-product row) | |
(transpose mat)))] | |
(map (partial row-mult mat2) | |
mat1))) | |
(defn test-my-mult | |
[n afn] | |
(let [xs (feature-vec n) | |
xst (transpose xs)] | |
(time (dorun (afn xst xs))))) | |
;; Example (yields a 23x23 matrix): | |
;; (test-my-mult 1000 i/mmult) => "Elapsed time: 32.626 msecs" | |
;; (test-my-mult 10000 i/mmult) => "Elapsed time: 628.841 msecs" | |
;; (test-my-mult 1000 matrix-mult) => "Elapsed time: 14.748 msecs" | |
;; (test-my-mult 10000 matrix-mult) => "Elapsed time: 434.128 msecs" | |
;; (test-my-mult 1000000 matrix-mult) => "Elapsed time: 375751.999 msecs" | |
;; Test from wikipedia | |
;; (def A [[14 9 3] [2 11 15] [0 12 17] [5 2 3]]) | |
;; (def B [[12 25] [9 10] [8 5]]) | |
;; user> (matrix-mult A B) | |
;; ((273 455) (243 235) (244 205) (102 160)) | |
(require '[incanter.core :as i]) | |
;; user> (i/mmult A B) | |
;; [273.0000 455.0000 | |
;; 243.0000 235.0000 | |
;; 244.0000 205.0000 | |
;; 102.0000 160.0000] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment