MATLAB 实现 单纯形算法

来源:互联网 发布:手机淘宝不能指纹支付 编辑:程序博客网 时间:2024/05/09 08:47

使用 MATLAB 实现单纯形法。

函数接口:

[x, case] = mysimplexMax(c, A, b, x0)

x0 是初始值,case = 0 表示有最优解,case = 1 表示无边界

解决如下线性规划标准形式问题:

argminx⃗ c⃗ Tx⃗ 

s.t.{Ax⃗ =b⃗ x⃗ 0

算法伪代码:

这里写图片描述

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);endend

以如下范例测试函数准确性:

maxx1,x2z=8x1+5x2

s.t.2x1+x210003x1+4x22400x1+x2700x1x2350x1,x20

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.0000ca =     0

最优解为 x1=320x2=360

1 0
原创粉丝点击