# 求解线性规划的Matlab 解法

Matlab 中线性规划的标准型为

[x,fval]=linprog(c,A,b,Aeq,beq,LB,UB,X0,OPTIONS)

f=[-2; -3; 5];
a=[-2,5,-1;1,3,1]; b=[-10;12];
aeq=[1,1,1];
beq=7;
[x,y]=linprog(f,a,b,aeq,beq,zeros(3,1));
x, y=-y


# Python解法

## Python Scipy库实现

# Scipy 库求解
from scipy import optimize
import numpy as np

res =
optimize.linprog(c,A,b,Aeq,beq,LB,UB,X0,OPTIOS)
# 目标最小值
print(res.fun)
# 最优解
print(rea.x)


from scipy import optimize
import numpy as np
c = np.array([2,3,-5])
A = np.array([[-2,5,-1],[1,3,1]])
B = np.array([-10,12])
Aeq = np.array([[1,1,1]])
Beq = np.array([7])

res = optimize.linprog(-c,A,B,Aeq,Beq)
print(res)


## Python plup库实现

# pulp库求解
import pulp
# 目标函数的系数
z = [2,3,1]
#约束
a = [[1,4,2],[3,2,0]]
b = [8, 6]
#确定最大化最小化问题，最大化只要把Min改成Max即可
m = pulp.LpProblem(sense=pulp.LpMinimize)
#定义三个变量放到列表中
x = [pulp.LpVariable(f'x{i}', lowBound=0) for i in [1,2,3]]
#定义目标函数，lpDot可以将两个列表的对应位相乘再加和
#相当于z[0]*x[0]+z[1]*x[1]+z[2]*x[2]
m += pulp.lpDot(z, x)
#设置约束条件
for i in range(len(a)):
m += (pulp.lpDot(a[i], x) >= b[i])
#求解
m.solve()
#输出结果
print(f'优化结果：{pulp.value(m.objective)}')
print(f'参数取值：{[pulp.value(var) for var in x]}')


## 一个十分有趣的例子

import pulp
import numpy as np
from pprint import pprint
def transportation_problem(costs, x_max, y_max):
row = len(costs)
col = len(costs[0])
prob = pulp.LpProblem('Transportation Problem',sense = pulp.LpMaximize)
var = [[pulp.LpVariable(f'x{i}{j}', lowBound=0,cat=pulp.LpInteger) for j in range(col)] for i in range(row)]
flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x]
prob += pulp.lpDot(flatten(var), costs.flatten())
for i in range(row):
prob += (pulp.lpSum(var[i]) <= x_max[i])
for j in range(col):
prob += (pulp.lpSum([var[i][j] for i in range(row)]) <= y_max[j])
#     print(prob)
prob.solve()
return {'objective':pulp.value(prob.objective),'var':[[pulp.value(var[i][j])for j in range(col)]for i in range(row)]}

if __name__ == '__main__':
costs = np.array([[500, 550, 630, 1000, 800, 700],
[800, 700, 600, 950, 900, 930],
[1000, 960, 840, 650, 600, 700],
[1200, 1040, 980, 860, 880, 780]])
max_plant = [76, 88, 96, 40]
max_cultivation = [42, 56, 44, 39, 60, 59]
res = transportation_problem(costs, max_plant,
max_cultivation)
print(f'最大值为{res["objective"]}')
print('各变量的取值为：')
pprint(res['var'])


Giving is a reward in itself.(给予本身就是一个奖赏)

08-15 2万+
03-12 8681
01-22 3万+
08-15 1万+
04-09
06-27 3090
09-09 2153
11-23 545
04-23 4020
03-31 3447
04-15 4351
07-20