【问题标题】:Counting the same rows of 2D matrix计算二维矩阵的相同行
【发布时间】:2017-12-29 10:26:23
【问题描述】:

我有一个两列矩阵。我需要将它设为三列,其中第三列显示前两个在输入矩阵中作为一行出现的次数。

基本上:输入

[1 1;
 1 1;
 1 2;
 1 2;
 1 3]

期望的输出:

[1 1 2;
 1 2 2;
 1 3 1]

我已经知道 accumarray 和 unique 的适当组合应该具有魅力。我只是不知道如何正确组合它们。

【问题讨论】:

    标签: matlab octave accumarray


    【解决方案1】:

    你说得对,uniqueaccumarray 非常适合这项任务:

    x = [1 1; 1 1; 1 2; 1 2; 1 3]; % input
    [~, v, w] = unique(x, 'rows', 'stable'); % unique indices and labels
    c = accumarray(w, 1); % counts
    y = [x(v,:) c]; % output
    

    如果您希望输出行按字典顺序排序,请删除 'stable' 标志。

    您也可以将accumarray 替换为bsxfun 以获得计数:

    c = sum(bsxfun(@eq, unique(w), w.'), 2);
    

    对于x的条目是正整数并且您希望按字典顺序输出的特殊情况,您还可以使用sparsefind,如下所示:

    x = [1 1; 1 1; 1 2; 1 2; 1 3]; % input
    [ii,jj,vv] = find(sparse(x(:,1), x(:,2), 1));
    y = [ii(:), jj(:), vv(:)]; % output
    

    【讨论】:

      【解决方案2】:

      一种可能的解决方案:

      clear
      a=...
      [1 1;
       1 1;
       1 2;
       1 2;
       1 3]
      
      [U,~,ic]=unique(a,'rows');
      [C] = histc(ic,unique(ic));
      Result=[U,C]
      

      【讨论】:

      • 很遗憾 histc 已被弃用。使用新的hitstcounts,您需要附加inf 并转置以实现相同的效果:C = histcounts(ic,[unique(ic); inf]).'
      猜你喜欢
      • 2010-12-30
      • 2019-03-25
      • 2021-04-12
      • 2016-10-30
      • 2022-12-10
      • 2012-03-15
      • 1970-01-01
      • 2012-10-01
      • 1970-01-01
      相关资源
      最近更新 更多