]> gitweb.michael.orlitzky.com - octave.git/blobdiff - perturb.m
Add the perturb() function and its tests.
[octave.git] / perturb.m
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