matlabmathinequalities

optimization of a linear system of inequalites


We are given four points, assumed to be ordered:

A = sort(randn(1,4))

I want to find the maximum possible number x in the interval 0<x<1 such that

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

Some examples:

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

Can you suggest a compact code to do this job, without having to list all the possible scenarios using if statements?


Solution

  • Having tried to do this with no if statements, I found that the readability of the code was greatly diminished. Note that there is only a single if statement in the code below while several other if statements could be substituted for the logical comparisons.

    All of your tests pass and the code remains very concise (9 lines without the comments and loop over all of the tests).

    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
    

    Output:

    x =
    
        0.3004
    
    
    x =
    
         1
    
    
    x =
    
        0.1000
    
    
    x =
    
         0
    
    
    x =
    
         1