From 79deafc20bc4cb3704f7f2cfcf845ed09d31eee3 Mon Sep 17 00:00:00 2001 From: Michael Orlitzky Date: Fri, 3 May 2013 21:51:30 -0400 Subject: [PATCH] Add rank_k_approximation() and its tests. --- rank_k_approximation.m | 19 +++++++++++++++++++ tests/rank_k_approximation_tests.m | 20 ++++++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 rank_k_approximation.m create mode 100644 tests/rank_k_approximation_tests.m diff --git a/rank_k_approximation.m b/rank_k_approximation.m new file mode 100644 index 0000000..ff42f58 --- /dev/null +++ b/rank_k_approximation.m @@ -0,0 +1,19 @@ +function Ak = rank_k_approximation(A,k) + % + % Compute the rank-k approximation to A from the ``k`` largest + % singular values of A. + % + % INPUT: + % + % - ``A`` -- The matrix to approximate. + % + % - ``k`` -- The rank of the resulting matrix; i.e. the number + % of (large) singular values to keep. + % + % OUTPUT: + % + % - ``Ak`` -- The rank-k approximation to ``A``. + % + [U, S, V] = svds(A, k); + Ak = U*S*V'; +end diff --git a/tests/rank_k_approximation_tests.m b/tests/rank_k_approximation_tests.m new file mode 100644 index 0000000..8288752 --- /dev/null +++ b/tests/rank_k_approximation_tests.m @@ -0,0 +1,20 @@ +U = [4/5, 3/5, 0 ; ... + 0 , 4/5, 3/5; ... + 3/5, 0 , 4/5 ]; + +S = [ 1, 0, 0; + 0, 2, 0; + 0, 0, 3 ]; + +V = [ 0, 1, 0; + 1, 0, 0; + 0, 0, 1 ]; + +A = U*S*V'; + +expected = A; +actual = rank_k_approximation(A, 3); + +unit_test_equals("Full rank approximation of a matrix is itself", ... + expected, ... + actual); -- 2.33.1