线性不等式系统的优化

optimization of a linear system of inequalites

我们得到四点,假设是有序的:

A = sort(randn(1,4))

我想在区间 0<x<1 中找到最大可能数 x 使得

A(1)<x<A(2) or A(3)<x<A(4)

一些例子:

A = [-1.4924    0.3004    1.6630     2.1204], x = 0.3004
A = [-0.4754    0.1353    0.6552     1.3873]; x = 1.0000
A = [-1.0213   -0.4521   -0.0905     0.1000]; x = 0.1000
A = [-1.8258   -0.5790   -0.4568    -0.1950]; x = 0.0000
A = [ 1.5000    2.0000    2.5000     3.0000]; x = 1.0000

你能建议一个紧凑的代码来完成这项工作,而不必使用 if 语句列出所有可能的场景吗?

在尝试不使用 if 语句的情况下执行此操作后,我发现代码的可读性大大降低。请注意,下面的代码中只有一个 if 语句,而其他几个 if 语句可以代替逻辑比较。

您的所有测试都通过了,代码仍然非常简洁(9 行没有注释并循环遍历所有测试)。

A = [[-1.4924    0.3004    1.6630     2.1204];
     [-0.4754    0.1353    0.6552     1.3873];
     [-1.0213   -0.4521   -0.0905     0.1000];
     [-1.8258   -0.5790   -0.4568    -0.1950];
     [ 1.5000    2.0000    2.5000     3.0000]];

for i = 1:size(A,1)
    % Reshape A so that each set of 2 entries are compared
    Atmp = reshape(A(i,:),2,2);

    % Find any valid entries
    Valid = Atmp > 0 & Atmp < 1;
    Ind_Valid = find(Valid == 1);

    if (~isempty(Ind_Valid))
        % If there are valid entries, return:
        %   max(A(ind),0) if the entry is the 1st of the pair
        %   max(A(ind),1) if the entry is the 2nd of the pair
        max_Ind = max(Ind_Valid);
        x = max(Atmp(max_Ind),mod(max_Ind,2))
    else
        % If there are no valid entries, return:
        %   0 if max A < 0
        %   1 if max A > 1
        x = max(Atmp(:)) > 0
    end
end

输出:

x =

    0.3004


x =

     1


x =

    0.1000


x =

     0


x =

     1