I wrote this code,but the plot is not what I want.how can I get the plot like below picture?
1 view (last 30 days)
Show older comments
% nonlinear constraint optimization function
prob=optimproblem
x=optimvar('x','LowerBound',-10,'UpperBound',10);
y=optimvar('y','LowerBound',-10);
obj=fcn2optimexpr(@objectivefunction,x,y)
prob.Objective=obj
constr=x.*y/2+(x+2).^2+(y-2).^2/2<=2 %polynomial inequality
prob.Constraints.ellipseparabola=constr
a=4
constexp=fcn2optimexpr(@constraintfunction,x,y,a)
consr2=constexp<=2
prob.Constraints.exponentialConstr=consr2
x0.x=-3
x0.y=3
options=optimoptions(prob,'Display','iter')
[sol,fval,exitflag,output]= solve(prob,x0,"options",options)
x0.x = -3;
x0.y = 4;
[sol2,fval2] = solve(prob,x0)
fprintf("Fval = %g\nNumber of iterations = %g\nNumber of function evals = %g.\n",...
fval,output.iterations,output.funcCount)
rng default
f = @(x,y) exp(x).*(4*x^2+2*y.^2+4*x.*y+2*y-1);
figure1
plot(sol.x,sol.y,"y*",'LineWidth',2)
hold on
plot(sol2.x,sol2.y,"r*",'LineWidth',2)
%rnge = [-5.5 -0.25 -0.25 7];
rng default
fcontour(f,'-.','LineWidth',2)
legend("nonlinear constraints problem","Location","northoutside")
hold off
% objective function
function f=objectivefunction(x,y)
f=exp(x).*(4*x^2+2*y.^2+4*x.*y+2*y-1)
end
%constraint
function constr=constraintfunction(x,y,a)
constr=x+2*exp((y-a)/4);
end
7 Comments
Voss
on 22 May 2022
It is plotting both "Local" and "Global" solutions, but they are the same, so you only see the last one plotted (one is on top of the other).
If you want the solution(s) from the example in the documentation, you should use the starting point(s) from the example in the documentation:
x0.x = -1;
x0.y = 1;
[sol2,fval2] = solve(prob,x0)
Also, you've got Local in black, Global in red (according to the comment), but then the legend labels black as Global, red as Local. Check on that.
Answers (0)
See Also
Categories
Find more on Nonlinear Optimization 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!