I need help for drawing a constraint in Matlab in 2D
Show older comments
Dear All,
I'm trying to draw a set of constraints but I got a wrong line for the constraint 2x1<=3 !!!! I need a vertical line !! I approciate any help from you !!!
Many Thanks,
Nadia
clear;clc;close;
%max 5x1+7x2;
%3x1+8x2<=12;
%x1+x2<=2;
%2x1<=3;
%x2<=4;
%x1,x2>=0;
%% plot the feasible region %Generate data
[x1,x2] = meshgrid(0:0.1:10);% i changed 0.1 to 0.01 to plot the fourth constraint
NB=5*x1+7*x2;
% Get True where condition applies, false where not.
cond1=3*x1+8*x2<=12; cond2=x1+x2<=2; cond3=2*x1<=3; cond4=x2<=2;
% Get boundaries of the condition
p1=(12-3*x1(1,:))/8;
p2=2-x1(1,:);
p3=3/2-x1(1,:);
p4=2-x2(1,:);
%Delete Areas whereCondition does not apply;
NB(~cond1)=NaN; NB(~cond2)=NaN; NB(~cond3)=NaN; NB(~cond4)=NaN;
%% Plot
[x2,h]=contourf(x1,x2,NB,0); % command contourf for filling the area between the contour levels
hold on
plot(x1(1,:),p1,'r','LineWidth',2); text(x1(1,20),p1(20), '\leftarrow Cond1'); %arbitrary location
plot(x1(1,:),p2,'k','LineWidth',2); text(x1(1,15),p2(15), '\leftarrow Cond2'); %arbitrary location
plot(x1(1,:),p3,'b','LineWidth',2); text(x1(1,20),p3(20), '\leftarrow Cond3'); %arbitrary location
plot(x1(1,:),p4,'b','LineWidth',2); text(x1(1,20),p4(20), '\leftarrow Cond3'); %arbitrary location
axis([0 5 0 5])
xlabel('x1')
ylabel('x2')
3 Comments
Sam Chak
on 7 Mar 2025
This looks very similar to the Linear Programming problem. Usually taught in the Operations Research courses, particularly in business schools, where it is often referred to as "Management Science" and is used to solve complex decision-making problems in areas like finance, logistics, and marketing.
Do you want to use the conventional way to plot the vertical line before the xline() command was introduced?
Sam Chak
on 7 Mar 2025
Woukd you also like to apply a colorful gradient translucent patch on the bounded feasible region as well?
nadia nadi
on 9 Mar 2025
Accepted Answer
More Answers (1)
I have no clue what you mean mathematically with what you wrote, but if you want to plot a vertical line, you can use xline():
x=linspace(0,2*pi);
plot(x,sin(x))
xline(pi)
yline(-0.5*sqrt(2))
legend({'data','xline','yline'})
Categories
Find more on Surface and Mesh Plots 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!

