]> gitweb.michael.orlitzky.com - octave.git/commitdiff
Add the perturb() function and its tests.
authorMichael Orlitzky <michael@orlitzky.com>
Mon, 25 Mar 2013 22:51:13 +0000 (18:51 -0400)
committerMichael Orlitzky <michael@orlitzky.com>
Mon, 25 Mar 2013 22:51:13 +0000 (18:51 -0400)
perturb.m [new file with mode: 0644]
tests/perturb_tests.m [new file with mode: 0644]

diff --git a/perturb.m b/perturb.m
new file mode 100644 (file)
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 (file)
index 0000000..f683336
--- /dev/null
@@ -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'));