【问题标题】:Provide value from row meets multliple conditions提供行中的值满足多个条件
【发布时间】:2020-02-11 23:22:48
【问题描述】:

我在 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。

【问题讨论】:

  • 你的问题是什么?你被困在哪里了?
  • 我一直在思考如何解决这个问题,我什至可以从哪里开始

标签: matlab matrix conditional-statements


【解决方案1】:

你可以通过大部分逻辑索引来做到这一点

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

【讨论】:

    【解决方案2】:

    您可以依次测试所有条件:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-25
      • 2018-03-02
      • 1970-01-01
      • 2020-03-31
      • 1970-01-01
      相关资源
      最近更新 更多