I am trying to optimize rosenbrock's function with fminsearch
and also drawing the point that gives the minimum value with point size being proportional to the iteration number at each iteration on the 2-D contour plot of rosenbrock's function, however that's not a good idea. As the point size gets bigger it's difficult to see other points. Instead I would like to plot the trajectory fminsearch
follows so that I can see the path clearly. How would one do that?
I couldn't find a way to do it as you only get a single point passed to the outputFcn
.
Here is an example of how I would like it to look like (just to clarify what I want):
options = optimset('outputFcn', @out, 'Display', 'iter');
x = [3.5 2.5 0.5 0.5];
y = [0 -2 -2 0];
[x,fval,eflag,output] = fminsearch(@rosenbrock_wrapper, [x(4), y(4)], options)
title 'Rosenbrock solution via fminsearch'
%Rosenbrock Function
function val = rosenbrock(x, y)
% a = 1.5, b = -1
val = (1 - x + 1.5) .^ 2 + 100 * (y + 1 - (x - 1.5) .^ 2) .^ 2;
end
%Rosenbrock Wrapper
function val = rosenbrock_wrapper(X)
val = rosenbrock(X(:, 1), X(:, 2));
end
%Output Function
function stop = out(x, optimValue, state)
stop = false;
switch state
case 'init'
fcontour(@rosenbrock, [0 3 -3 3], 'MeshDensity',50, 'LineWidth', 2, 'LevelList', 1:5:300);
hold on;
case 'iter'
plot(x(1), x(2), '.', 'MarkerSize', optimValue.iteration + 1);
end
end
If you want to plot the progress of the optimization problem real time, you can use the
PlotFcn
option offminsearch
(see docs for more info).Alternatively, you can let the output function assign the x,y data to the base workspace after all iterations. Then you can just plot them like you are used to.
And to get the data after the optimization, you just have to do: