Permalink
Browse files

Merge pull request #79 from ebrevdo/master

Added :type parameter to decomp-svd to allow compact- or values-only- SVD.
  • Loading branch information...
2 parents d590521 + b758f24 commit 3a7383cdc7f15dc66d75c265a9ce76634ad7edc6 @alexott alexott committed Jun 1, 2012
Showing with 40 additions and 7 deletions.
  1. +20 −7 modules/incanter-core/src/incanter/core.clj
  2. +20 −0 modules/incanter-core/test/incanter/core_tests.clj
@@ -876,29 +876,42 @@
" Returns the Singular Value Decomposition (SVD) of the given matrix. Equivalent to
R's svd function.
+ Optional parameters:
+ :type -- one of :full, :compact, or :values. default is :full
+ if :full, returns the full SVD
+ if :compact, returns the compact SVD
+ if :values, only the singular values are calculated
+
Returns:
a map containing:
- :S -- the diagonal matrix of singular values
+ :S -- the diagonal matrix of singular values S (the diagonal in vector form)
:U -- the left singular vectors U
:V -- the right singular vectors V
-
Examples:
(use 'incanter.core)
(def foo (matrix (range 9) 3))
(decomp-foo foo)
+ (decomp-foo foo :type :full)
+ (decomp-foo foo :type :compact)
+ (decomp-foo foo :type :values)
References:
http://en.wikipedia.org/wiki/Singular_value_decomposition
http://incanter.org/docs/parallelcolt/api/cern/colt/matrix/tdouble/algo/decomposition/DoubleSingularValueDecompositionDC.html
"
- ([mat]
- (let [result (DenseDoubleSingularValueDecomposition. mat, true, true)]
- {:S (diag (Matrix. (.getS result)))
- :U (Matrix. (.getU result))
- :V (Matrix. (.getV result))})))
+ ([mat & {:keys [type] :or {type :full}}]
+ (let [type (or type :full)
+ want-uv (not= type :values)
+ want-whole-uv (= type :full)
+ result (DenseDoubleSingularValueDecomposition. mat want-uv want-whole-uv)]
+ (if (= type :values)
+ {:S (diag (Matrix. (.getS result)))}
+ {:S (diag (Matrix. (.getS result)))
+ :U (Matrix. (.getU result))
+ :V (Matrix. (.getV result))}))))
@@ -429,6 +429,26 @@
;; calculate the product of values in a vector or 1D matrix
(is (= (prod [1 2 3 4 5 6]) 720.0)))
+(deftest decomp-svd-test
+ (let [m (matrix [[1 0] [0 1] [0 0]])
+ expect-full {:U (diag [1 1 1])
+ :S '(1.0 1.0)
+ :V (diag [1 1])}
+ expect-compact {:U m
+ :S '(1.0 1.0)
+ :V (diag [1 1])}
+ expect-values {:S '(1.0 1.0)}
+ check (fn [type mtest]
+ (let [mtrue (decomp-svd m :type type)]
+ (testing (str "svd " type)
+ (is (= (:U mtrue) (:U mtest)))
+ (is (= (:S mtrue) (:S mtest)))
+ (is (= (:V mtrue) (:V mtest))))))]
+ (check nil expect-full)
+ (check :full expect-full)
+ (check :compact expect-compact)
+ (check :values expect-values)))
+
(deftest test-metadata
(let [md {:name "metadata test"}

0 comments on commit 3a7383c

Please sign in to comment.