 (defn proj-vec [xs ys]
   "This computes the projection of ys orthogonally onto the vector spanned by xs"
   (let [coeff (/ (dot xs ys) (dot xs xs))]
-    (ic.core/mult coeff xs)))
+    (* coeff xs)))
 
 
 (defn factor-matrix [data xs]
   "As in the Gram-Shmidt process; we can 'factor out' the vector xs from all the vectors in data,
   such that there is no remaining variance in the xs direction within the data."
-  (ic.core/matrix (mapv #(ic.core/minus % (proj-vec xs %)) data)))
-
-
-(defn mean-vector [data] 
-  (if (= (first (ic.core/dim data)) 1)
-    (ic.core/matrix data)
-    (ic.core/matrix (mapv ic.stats/mean (zip (tr/trace data))))))
+  (matrix (mapv #(- % (proj-vec xs %)) data)))
 
 
 (defn centered-data [data]
-  (let [data-cntr (ic.core/trans (mean-vector data))]
-    (mapv #(ic.core/minus % data-cntr) data)))
+  (- data (mean data)))
 
 
 ; Will eventually also want to add last-pcs

(defn xtxr [data start-vec]
  "Will need to rename this and some of the inner variables to be easier to read...
  Computes an inner step of the power-iteration process"
  (let [n-rows (count (first data))
        curr-vec (ic.core/trans (repeatv n-rows 0))]
    (loop [data data curr-vec curr-vec]
      (if-let [row (first data)]
        (recur (rest data)
               (ic.core/plus (tr/trace curr-vec)
                             (tr/trace (ic.core/mult (dot row start-vec) row))))
        curr-vec))))



(ns pca
  (:refer-clojure :exclude [* - + == /])
  (:use utils)
  (:use clojure.core.matrix)
  (:use clojure.core.matrix.stats)
  (:use clojure.core.matrix.operators)
  (:use utils matrix-utils))

(set-current-implementation :vectorz)


(set! *unchecked-math* true)


(defn repeatv [n x]
  "Utility function for making a vector of length n composed entirely of x"
  (matrix (into [] (repeat n x))))


; Should maybe hide this inside power-iteration and have that function wrap it's current
