How to plot the trajectory that fminsearch follows?

27 次查看(过去 30 天)
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 my plot:
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

采纳的回答

Matt J
Matt J 2020-11-23
编辑:Matt J 2020-11-23
trajectory=doIt();
fcontour(@rosenbrock, [0 3 -3 3],'LineColor', '#00FFFF', 'MeshDensity',50,...
'LineWidth', 2, 'LevelList', 1:25:300);
hold on
plot(trajectory(1,:),trajectory(2,:),'ks-','MarkerFaceColor','k')
plot(trajectory(1,end),trajectory(2,end),'ro','MarkerSize',20)
hold off
title 'Rosenbrock solution via fminsearch'
function history=doIt
options = optimset('outputFcn', @out, 'Display', 'none');
x = [3.5 2.5 0.5 0.5];
y = [0 -2 -2 0];
history=[];
[x,fval,eflag,output] = fminsearch(@rosenbrock_wrapper, [x(4), y(4)], options);
%Output Function
function stop = out(x, optimValue, state)
stop = false;
switch state
case 'iter'
history=[history,x(:)];
end
end
end
%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
  1 个评论
Burak
Burak 2020-11-23
编辑:Burak 2020-11-23
Just what I was looking for, thank you! I couldn't think of a way to do it by parameterization. Oh by the way, I just moved that plot part inside the output function in 'done' case.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Colormaps 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by