How to plot 3D suraface and contour lines?

1 view (last 30 days)
I want to plot the function
X0=[0;0];
lb=[-10;10];
ub=[-10;10];
f=@(x)(2*x(1)+20/x(1)+2*x(2)+20/x(2)+120);
x=fmincon(f,X0,[],[],[],[],lb,ub)
Initial point is a local minimum that satisfies the constraints. Optimization completed because at the initial point, the objective function is non-decreasing in feasible directions to within the value of the optimality tolerance, and constraints are satisfied to within the value of the constraint tolerance.
x = 2×1
-10 10
How to plot the 3D surface and also the contour lines?

Accepted Answer

Bjorn Gustavsson
Bjorn Gustavsson on 2 Jun 2022
To effectively use matlab sometimes one has to make functions vectorized - such that you can feed the function arrays and get all results at once. This is such a case. Your f works well for the optimization. But if you define it this way:
f=@(x1,x2)(2*x1+20./x1+2*x2+20./x2+120);
You can still run it through fmincon:
X0=[1;1]; % Note that your function is undefined at [0, 0] due to the 2 1/x-terms
lb=[-10;-10]; % Note that I've changed the bounds. Yours constrained the solution to be
ub=[10;10]; % X1 = -10 and X2 = 10
x=fmincon(@(X) f(X(1),X(2)),X0,[],[],[],[],lb,ub);
and then effectively plot the function with surf and contour:
[x1,x2] = meshgrid(linspace(lb(1),ub(1),100),linspace(lb(2),ub(2),100));
surf(x1,x2,f(x1,x2)),shading flat
hold on
contour(x1,x2,f(x1,x2),-200:30:400)
HTH

More Answers (0)

Categories

Find more on Contour Plots in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!