MATLAB 实现 单纯形算法
使用 MATLAB 实现单纯形法。
函数接口:
[x, case] = mysimplexMax(c, A, b, x0)
x0 是初始值,case = 0 表示有最优解,case = 1 表示无边界
解决如下线性规划标准形式问题:
算法伪代码:
MATLAB 代码实现:
function [x, result_case] = mysimplexMax(c, A, b, x0)
ind_B = find(x0 ~=0);
ind_N = find(x0 == 0);
while (1)
B = A(:, ind_B);
N = A(:, ind_N);
x_B = x0(ind_B);
x_N = x0(ind_N);
c_B = c(ind_B);
c_N = c(ind_N);
s = c_N - N' * inv(B)' * c_B;
%'
if isempty(find(sign(s) > 0))
% found optimal solution
x = x0;
result_case = 0;
return
end
% 保证 s 有正数
% 选最大的正检验数作为进基变量 q
[max_q i_q] = max(s);
q = ind_N(i_q);
d = B \ A(:, q);
if isempty(find(sign(d) > 0))
% unbound case
x = [];
result_case = 1;
break;
end
% 保证 d 有正数
% 选择最小非负ratio 作为离基变量 p
ratio_array = x_B./d;
ratio = min(ratio_array((ratio_array > 0)));
% 更新 x0 的值
x0(ind_B) = x_B - ratio * d;
e_iq = zeros(length(x_N), 1);
e_iq(i_q) = 1;
x0(ind_N) = x_N + ratio * e_iq;
% 更新基本量,非基变量集合
ind_B = find(x0 ~=0);
ind_N = find(x0 == 0);
end
end
---------------------
本文来自 子辰曦 的**** 博客 ,全文地址请点击:https://blog.****.net/u012675539/article/details/50177655?utm_source=copy
以如下范例测试函数准确性:
A = [2 1 1 0 0 0;3 4 0 1 0 0;1 1 0 0 1 0;1 -1 0 0 0 1];
b = [1000; 2400; 700; 350];
c = [8; 5; 0; 0; 0; 0];
x0 = [0; 0; b];
[x, ca] = mysimplexMax(c, A, b, x0)
结果输出正确:
x =
320.0000
360.0000
0
0
20.0000
390.0000
ca =
0
最优解为 x1=320 ,x2=360