Add extended_rosenbrock_gradient1() and its tests.
authorMichael Orlitzky <michael@orlitzky.com>
Fri, 8 Mar 2013 15:12:21 +0000 (10:12 -0500)
committerMichael Orlitzky <michael@orlitzky.com>
Fri, 8 Mar 2013 15:12:21 +0000 (10:12 -0500)
optimization/test_functions/extended_rosenbrock_gradient1.m [new file with mode: 0644]
tests/extended_rosenbrock_gradient1_tests.m [new file with mode: 0644]

diff --git a/optimization/test_functions/extended_rosenbrock_gradient1.m b/optimization/test_functions/extended_rosenbrock_gradient1.m
new file mode 100644 (file)
index 0000000..2fd3c8c
--- /dev/null
@@ -0,0 +1,31 @@
+function g = extended_rosenbrock_gradient1(x)
+  ##
+  ## The gradient of the extended Rosenbrock function. See
+  ## extended_rosenbrock1.m for more information.
+  ##
+  ## Since the number of arguments is variable, we take a vector
+  ## instead of its individual components.
+  ##
+  n = length(x);
+
+  if (odd(n))
+    ## 'm' below must be an integer.
+    g = NA;
+    return;
+  end
+
+  m = n / 2;
+  g = zeros(n, 1);
+
+  % The extended Rosenbrock is simply a sum of Rosenbrock
+  % applications.
+  for k = [ 1 : m ]
+    y1 = x(2*k - 1);
+    y2 = x(2*k);
+
+    g_k = rosenbrock_gradient(y1, y2);
+
+    g(2*k - 1) = g(2*k - 1) + g_k(1);
+    g(2*k) = g(2*k) + g_k(2);
+  end
+end
diff --git a/tests/extended_rosenbrock_gradient1_tests.m b/tests/extended_rosenbrock_gradient1_tests.m
new file mode 100644 (file)
index 0000000..cc42544
--- /dev/null
@@ -0,0 +1,13 @@
+## The gradient should be zero at the optimal point.
+
+for m = [ 1 : 10 ]
+  x = repmat([1;1], m, 1);
+
+  msg = sprintf("extended_rosenbrock_gradient1([1;1;...]) == 0 (m = %d)", m);
+  unit_test_equals(msg, 0, extended_rosenbrock_gradient1(x));
+end
+
+## It should fail with the wrong number of coordinates.
+g = extended_rosenbrock_gradient1([1;2;3]);
+msg = "extended_rosenbrock_gradient1 fails when length(x) is odd";
+unit_test_equals(msg, true, isna(g));