How to visualize the iterations of an optimization problem ?
8 views (last 30 days)
Show older comments
Hi everybody,
I recently started to learn how to optimize a continuous function and I want to get a figure like the one I attached as one of the outputs but I do not know how to code that.
prob = optimproblem
%defining variables
x= optimvar('x',"LowerBound",-2.5,'UpperBound',2.5);
y= optimvar('y',"LowerBound",-2.5,'UpperBound',2.5);
%ndefining objective function
prob.Objective=log(1+3.*(y-(x.^3-3)).^2+(x-4/3).^2);
%setting initial guess
initialpt.x=-1
initialpt.y=2
%options
options=optimoptions(prob,'Display','iter')
[sol,fval,exitflag,output]=solve(prob,initialpt,'options',options);
disp("# of function evaluations:"+output.funcCount)
fval
sol
exitflag
I want to have the following figure as an output:
Thank you

0 Comments
Accepted Answer
Matt J
on 3 Jul 2021
Edited: Matt J
on 3 Jul 2021
function main
xhist=[];
prob = optimproblem
%defining variables
x= optimvar('x',"LowerBound",-2.5,'UpperBound',2.5);
y= optimvar('y',"LowerBound",-2.5,'UpperBound',2.5);
%ndefining objective function
prob.Objective=log(1+3.*(y-(x.^3-3)).^2+(x-4/3).^2);
%setting initial guess
initialpt.x=-1;
initialpt.y=2;
%options
options=optimoptions(prob,'Display','iter','OutputFcn',@histfunc);
[sol,fval,exitflag,output]=solve(prob,initialpt,'options',options);
fcontour( @(x,y) log(1+3.*(y-(x.^3-3)).^2+(x-4/3).^2));
hold on
plot(xhist(1,:), xhist(2,:),'-om','MarkerFaceColor','b');
hold off
function stop = histfunc(x,optimValues,state)
stop = 0;
if state~="iter"; return; end
xhist=[xhist,x(:)];
end
end
More Answers (0)
See Also
Categories
Find more on Get Started with Problem-Based Optimization and Equations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!