【问题标题】:remove non matching elements from matrix从矩阵中删除不匹配的元素
【发布时间】:2019-03-23 05:40:10
【问题描述】:

我正在尝试比较两个矩阵 AB。如果A 的前两列中的元素与B 中的元素匹配,我想从A 中删除所有不匹配的行。 B 中的第三列不应计入比较中。

A = [1 2 3      B = [1 2 8
     3 4 5           3 4 5]
     6 7 8]

想要的结果:

A = [1 2 3
     3 4 5]

到目前为止,我只找到了删除重复条目的方法,这与我想要的完全相反。我该怎么做?

【问题讨论】:

    标签: matrix octave rows


    【解决方案1】:

    您可以有效地使用ismember 完成此任务:

    % Input matrices
    A = [1 2 3; 3 4 5; 7 8 9];
    B = [1 2 8; 3 4 5];
    
    A1 = A(:,1:2);                   % Extract first two columns for both matrices
    B1 = B(:,1:2);
    [~,ii] = ismember(A1,B1,'rows'); % Returns which rows in A1 are also in B1
    ii = ii(ii>0);                   % Where ii is zero, it's a non-matching row
    A(ii,:)                          % Index to keep only matching rows
    

    所有这些都可以写得更紧凑,但我想先展示一步一步的过程:

    [~,ii] = ismember(A(:,1:2),B(:,1:2),'rows');
    A(ii(ii>0),:)
    

    【讨论】:

      【解决方案2】:
      A = [1 2 3;3 4 5;7 8 9];
      B = [1 2 8; 3 4 5];
      tmp = min([size(A,1) size(B,1)]); % get size to loop over
      k = false(tmp,1); % storage counter
      for ii = 1:tmp 
          if all(A(ii,1:2)==B(ii,1:2)) % if the first two columns match
              k(ii)=true; % store
          end
      end
      
      C = A(k,:) % extract requested rows
      

      【讨论】:

        猜你喜欢
        • 2014-09-21
        • 2012-02-13
        • 2019-11-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多