# 2 MATLAB软件求解

（1）建立M文件fun.m

``````function f = fun(x)
f =F(x);
``````

（2）若约束条件中有非线性约束

``````G(x)<=0或Ceq(x)=0,则建立M文件nonlcon.m定义函数G(x)与Ceq(x)
function [G,Ceq] = nonlcon(x)
G = ...;
Ceq =...;
``````

（3）建立主程序

# 3 例题

min f(x) = -2×1-x2

g1(x) = 25 -x12-x22

g2(x) = 7-x12+x22

0<=x1<=5,0<=x2<=10

（1）先建立M-文件fun.m定义

``````function f = fun(x);
f = -2*x(1)-x(2);
``````

（2）再建立M文件mycon2.m定义非线性约束

``````function [g,ceq] = mycon2(x)
g = [x(1)^2+x(2)^2-25;x(1)^2-x(2)^2-7]
``````

（3）主程序fxx.m

``````x0 =[3;2.5];
VLB =[0,0];下限
VUB =[5,10];上限
[x,fval,] = fmincon('fun',x0,[],[],[],[],VLB,VUB,'mycon2']没有线性约束，参数设置为[]
``````

# 4 应用实例

（1）符号说明
(ai,bi)第i个工地的位置坐标
(xj,yj)第j个料场的位置坐标
di第i个工地的水泥日用量
ej第j个料场的水泥日存储量
xij第j个料场向第i个工地的水泥日运量
（2）模型建立

（3）MATLAB求解

``````clear
a=[1.25 8.75 0.5 5.75 3 7.25];
b=[1.25 0.75 4.75 5 6.5 7.75];
d=[3 5 4 7 6 11];
x=[5 2];
y=[1 7];
e=[20 20];
for  i=1:6
for j=1:2
aa(i,j)=sqrt((x(j)-a(i))^2+(y(j)-b(i))^2);
end
end
CC=[aa(:,1); aa(:,2)]';
A=[1 1 1 1 1 1 0 0 0 0 0 0
0 0 0 0 0 0 1 1 1 1 1 1];
B=[20;20];
Aeq=[1 0 0 0 0 0 1 0 0 0 0 0
0 1 0 0 0 0 0 1 0 0 0 0
0 0 1 0 0 0 0 0 1 0 0 0
0 0 0 1 0 0 0 0 0 1 0 0
0 0 0 0 1 0 0 0 0 0 1 0
0 0 0 0 0 1 0 0 0 0 0 1 ];
beq=[d(1);d(2);d(3);d(4);d(5);d(6)];
VLB=[0 0 0 0 0 0 0 0 0 0 0 0];VUB=[];
x0=[1 2 3 0 1 0 0 1 0 1 0 1];
[xx,fval]=linprog(CC,A,B,Aeq,beq,VLB,VUB,x0)
``````

x =[ 3.0000 5.0000 0.0000 7.0000 0.0000 1.0000 0.0000 0.0000 4.0000 0.0000 6.0000 10.0000]’

fval = 136.2275

# 5 课后作业

Max Z = 1000×1+1440×2+2520×3

5×1 +8×2+12×3 = 27000
x1=0 or 1000<=x1<=2000
x2=0 or 10000<=x2<=2000
x3 =0 or10000<=x3<=2000