How to plot the trajectory that fminsearch follows?

조회 수: 27 (최근 30일)
Burak
Burak 2020년 11월 23일
편집: Burak 2020년 11월 23일
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