0

順序付けられていると仮定して、次の 4 つのポイントが与えられます。

A = sort(randn(1,4))

x間隔で可能0<x<1な最大数を見つけたい

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ステートメントを使用して考えられるすべてのシナリオをリストすることなく、このジョブを実行するためのコンパクトなコードを提案できますか?

4

1 に答える 1

0

if ステートメントを使用せずにこれを実行しようとしたところ、コードの可読性が大幅に低下することがわかりました。以下のコードには if ステートメントが 1 つしかないことに注意してください。論理比較の代わりに他の 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
于 2016-03-25T15:18:10.080 に答える