I wrote this code,but the plot is not what I want.how can I get the plot like below picture?

1 次查看(过去 30 天)
% 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 个评论
sogol bandekian
sogol bandekian 2022-5-22
it is not generate local solution,why?
f = @(x,y) exp(x).*(4*x.^2+2*y.^2+4*x.*y+2*y-1);
w=@(x,y) x.*y/2+(x+2).^2+(y-2).^2/2-2;
rnge = [-5.5 -0.25 -0.25 7];
fimplicit(w,'kx-') %plot implicit function with consideration constraint
axis(rnge)
hold on
fcontour(f,rnge,'-.','LineWidth',2,'LevelList',logspace(-1,1))
plot(sol.x,sol.y,"ko",'LineWidth',2)
plot(sol2.x,sol2.y,"ro",'LineWidth',2) %Global solution
legend('nonlinear constraints problem','f Contours','Global Solution','Local Solution',"Location","northoutside")
hold off
Voss
Voss 2022-5-22
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.

请先登录,再进行评论。

回答(0 个)

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by