Minimize Rosenbrock’s function (32.1.2) using the reflection-contraction-expansion version of the Nelder-Mead method. Use a random starting point
randn(2, 1) as one vertex \(A\) of the initial triangle, and let other vertices be \(A + \mathbf e_1\text{,}\) \(A+\mathbf e_2\text{.}\) Plot the path of the search.
Solution.
The code is mostly the same as in Example 33.2.1, with additional lines noted in comments.
f = @(x) (x(1)-1)^2 + 100*(x(1)^2 - x(2))^2;
A = randn(2, 1);
B = A + [1; 0];
C = A + [0; 1];
T = [A B C];
max_tries = 10000;
path = zeros(2, max_tries);
for k = 1:max_tries
path(:, k) = mean(T, 2);
if max(abs(T - mean(T, 2))) < 1e-6
break
end
values = [f(T(:,1)) f(T(:,2)) f(T(:,3))];
[fmax, ind] = max(values);
M = (sum(T, 2) - T(:, ind))/2;
R = 2*M - T(:, ind);
if f(R) < fmax
E = 2*R - M; % consider expansion
if f(E) < f(R)
T(:, ind) = E; % choose to expand
else
T(:, ind) = R; % choose to reflect
end
else
[fmin, ind] = min(values);
T = (T + T(:, ind))/2;
end
end
plot(path(1, 1:k), path(2, 1:k), '-+')
if k < max_tries
x = mean(T, 2);
fprintf('Found x = (%g, %g) with f(x) = %g after %d steps\n', x, f(x), k);
else
disp('Failed to converge')
end
