首页 > 解决方案 > 提供行中的值满足多个条件

问题描述

我在 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;]

我需要返回满足多个条件的行。

  1. 对于要包含的任何行,第一列和第二列必须相等。

  2. 然后我想要第 2 列中的最大值。

  3. 如果有两个候选人同时满足条件 1 和 2,我想选择第 3 列中数字最小的那个。

所以在上面的例子中,我想输入数据矩阵并返回 13。

标签: matlabmatrixconditional-statements

解决方案


您可以通过大多数逻辑索引来做到这一点

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

您可以在一行中完成所有这些操作,但这并不漂亮,而且您要计算条件 1 两次:

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

推荐阅读