Minimize Rosenbrock’s function (32.1.2) using line search in the direction of steepest descent, \(-\nabla f\text{,}\) at each step. Use a random starting point
randn(2, 1). Plot the path of the search.
Solution.
The gradient of Rosenbrock’s function is
\begin{equation}
\begin{pmatrix} 2(x_1-1) + 400x_1(x_1^2-x_2) \\ -200(x_1^2 - x_2)\end{pmatrix}\tag{32.1.3}
\end{equation}
The code uses a matrix
path to record the path taken by the search.f = @(x) (x(1)-1).^2 + 100*(x(1).^2 - x(2)).^2;
fg = @(x) [2*(x(1)-1) + 400*x(1)*(x(1).^2 - x(2)); -200*(x(1).^2 - x(2))];
x = randn(2, 1);
max_tries = 10000;
path = zeros(2, max_tries);
for k = 1:max_tries
path(:, k) = x;
g = -fg(x); % direction of descent
t_min = fminbnd(@(t) f(x + t*g), 0, 1);
dx = t_min*g;
x = x + dx;
if norm(dx) < 1e-6
break
end
end
plot(path(1, 1:k), path(2, 1:k), '-+')
if k < max_tries
fprintf('Found x = (%g, %g) with f(x) = %g after %d steps\n', x, f(x), k);
else
disp('Failed to converge')
end
Whether the code converges or fails depends on the initial point. Often it fails despite being on the right track, because of too many tiny zigzagging steps.
