【问题标题】:Fast way to compare rows of a matrix two by two?两两比较矩阵行的快速方法?
【发布时间】:2015-04-13 19:38:33
【问题描述】:

我有一个代码,在运行过程中重复了几次。此代码两两比较C 的行。运行需要很长时间,特别是对于大型C。我正在寻找一种快速的方法来运行它。我使用了a(ismember(a,b))) 而不是intersect(a,b)

     I = size (C,1);
     for i = 1 : I-1,
        for j = i+1 : I,
            a=C(i,:);
            b=C(j,:);
            if sum(a(ismember(a,b)))-sum(b)==0,
                n = n+1;
                K(n) = j;
                K1(n) = i;
            end
        end
    end

【问题讨论】:

  • C 的典型数据大小是多少?
  • 感谢您的提示。 C 的行数通常最多可达 1500 行。它的列更少(最多 5 个)。
  • 你想用这个做什么?
  • @knedlsepp:我想找到多余的行。冗余行是那些具有其他行和零元素的子集的行。例如如果C=[17 18 5;3 5 7;17 18 0;4 17 2;5 0 0],那么C(3,:)C(5,:) 是多余的。因此n=2K=[3 5 5]K1n=[1 1 2]
  • @Meher81:您的原始代码与您在评论中描述的不完全一致。这仅在C 的条目不是负数时有效。

标签: performance matlab matrix vectorization


【解决方案1】:

这将是一种vectorized 方法-

%// Get the size of C and pairwise indices
N = size(C,1);
[Y,X] = find(bsxfun(@gt,[1:N]',[1:N])); %//'

%// Form the two pairs
p1 = C(X,:);
p2 = C(Y,:);

%// Get the matches for each element in a row against all other elements in
%// the matching row pair combinations. This would be equivalent to
%// ISMEMBER implementation in the original code
matches = squeeze(any(bsxfun(@eq,permute(p1,[3 2 1]),permute(p2,[2 3 1])),1));
matches = reshape(matches,[],numel(Y)); %//for special case when C has 2 rows

%// Get linear indices that satisfy the equality criteria from original code
idx = find(sum(matches.'.*p1,2) == sum(p2,2)); %//'

%// Store the row and column information from the linear indices
K_vectorized = Y(idx);
K1_vectorized = X(idx);

【讨论】:

  • 您的代码不适用于某些 C。我找不到原因。例如,请测试C=[3,4,0,0;4,8,0,0;]
  • @Divakar:C 包含零和正整数。
  • @Meher81 必须添加一行来处理这种特殊情况。立即查看。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-08
  • 2020-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-27
相关资源
最近更新 更多