From 79f2b66bf6273f0f761d414613c69873aba0307b Mon Sep 17 00:00:00 2001 From: Michael Orlitzky Date: Mon, 25 Mar 2013 18:51:13 -0400 Subject: [PATCH] Add the perturb() function and its tests. --- perturb.m | 34 ++++++++++++++++++++++++++++++++++ tests/perturb_tests.m | 7 +++++++ 2 files changed, 41 insertions(+) create mode 100644 perturb.m create mode 100644 tests/perturb_tests.m diff --git a/perturb.m b/perturb.m new file mode 100644 index 0000000..70dbef2 --- /dev/null +++ b/perturb.m @@ -0,0 +1,34 @@ +function x_hat = perturb(x, epsilon) + % + % Generate a perturbed copy of ``x``, that is, a vector (or matrix) + % of the form ``x + dx`` where ``dx`` has same dimensions as x and + % negligible norm. + % + % INPUT: + % + % ``x`` -- The vector or matrix to perturb. + % + % ``epsilon`` -- An upper bound for the entries of ``dx``. + % + % OUTPUT: + % + % ``x_hat`` -- A perturbed copy of ``x``; ``x_hat == x + dx``. + % + + % If no epsilon was given, make something up. + if (nargin < 2) + epsilon = 1e-10; + end + + % This creates a vector or matrix whose entries lie in [-1,1]. + dx = 2*rand(size(x)) - 1; + + % First normalize delta, using the infinity norm for speed (since + % it doesn't matter). + dx = dx / norm(dx, 'inf'); + + % Now scale it so that its largest entry is + dx = dx * norm(x,'inf') * epsilon; + + x_hat = x + dx; +end diff --git a/tests/perturb_tests.m b/tests/perturb_tests.m new file mode 100644 index 0000000..f683336 --- /dev/null +++ b/tests/perturb_tests.m @@ -0,0 +1,7 @@ +A = rand(10); +A_hat = perturb(A, 1e-12); +dA = A_hat - A; + +unit_test_equals("dA has the correct infinity norm", ... + 1e-12, ... + norm(dA, 'inf')); -- 2.33.1