user30609
user30609

Reputation: 264

Provide value from row meets multliple conditions

I have three columns of data in MATLAB...

A = [ 10.0000   10.0000   22.9401;
    9.0000   11.0000  302.5402;
    9.0000   11.0000  285.7156;
    9.0000   11.0000  294.7599;
    9.0000   11.0000  301.2963;
    9.0000   11.0000  288.3905;
    9.0000   11.0000  301.0232;
    9.0000   11.0000  300.4630;
    9.0000   11.0000  287.3316;
    9.0000   11.0000  265.4248;
    9.0000   11.0000  297.4152;
   11.0000   11.0000   32.7959;
   11.0000   11.0000   32.2272;
   10.0000   12.0000  304.5999;]

I need to return the row which meets a number of conditions.

  1. For any row to be be included, the first and second columns must be equal.

  2. Then I would like the largest value from column 2.

  3. If there is a case when there are two candidates that meet conditions 1 and 2, I would like to choose the one with the smallest number in column 3.

So in the above example I would like to input the matrix of data and it return with 13.

Upvotes: 0

Views: 42

Answers (2)

Wolfie
Wolfie

Reputation: 30046

You can do this with mostly just logical indexing

% Add a row index as a 4th column to A. 
% This is so we can track the original row number as we filter A down.
A(:,4) = (1:size(A,1)).';
% Filter A to satisfy condition (1); column 1 value == column 2 value
Afilt = A( A(:,1) == A(:,2), : );
% Filter again to leave only the rows which satisfy condition (2)
% Also sort on column 3 so that row 1 has the lowest value in column 3
Afilt = sortrows( Afilt( Afilt(:,1) == max(Afilt(:,1)), : ), 3, 'ascend' );
% Get the first value in column 4, which corresponds to the lowest value in col 3
idx = Afilt(1,4);

You could do this all in one line, but it's not pretty and you're computing condition 1 twice:

[~,idx] = min( A(:,3) .* 1./(A(:,1)==A(:,2) & A(:,1)==max(A(A(:,1)==A(:,2),1))) );

Upvotes: 2

obchardon
obchardon

Reputation: 10792

You can test all your conditions successively:

% First column = Second column
ind1     = find(A(:,1) == A(:,2))
% Find the maximum value from the second column that also meet the first condition
ind2     = find(A(ind1,2) == max(A(ind1,2)))
% Get the minimal value on the last column that also meet the first and second condition
[~,ind3] = min(A(ind1(ind2),3))

% Get the result
row = ind1(ind2(ind3))

Upvotes: 1

Related Questions