【问题标题】:How to quickly get the array of multiplicities如何快速获得多重性数组
【发布时间】:2014-02-11 19:04:25
【问题描述】:

获取数组A 并同时输出unique(A) 的最快方法是什么? A] 的唯一数组元素的集合以及多重性数组,它在 A 中将 unique(A) 的第 i 个条目的第 i 个多重性放在其第 i 个位置。

这是一口,所以这里有一个例子。给定A=[1 1 3 1 4 5 3],我想要:

  1. unique(A)=[1 3 4 5]
  2. mult = [3 2 1 1]

这可以通过一个乏味的 for 循环来完成,但想知道是否有办法利用 MATLAB 的数组特性。

【问题讨论】:

    标签: arrays matlab unique accumarray


    【解决方案1】:
    uA = unique(A);
    mult = histc(A,uA);
    

    或者:

    uA = unique(A);
    mult = sum(bsxfun(@eq, uA(:).', A(:)));
    

    基准测试

    N = 100;
    A = randi(N,1,2*N); %// size 1 x 2*N
    
    %// Luis Mendo, first approach
    tic
    for iter = 1:1e3;
        uA = unique(A);
        mult = histc(A,uA);
    end
    toc
    
    %// Luis Mendo, second approach    
    tic
    for iter = 1:1e3;
        uA = unique(A);
        mult = sum(bsxfun(@eq, uA(:).', A(:)));
    end
    toc
    
    %'// chappjc
    tic
    for iter = 1:1e3;
        [uA,~,ic] = unique(A);    % uA(ic) == A
        mult= accumarray(ic.',1);
    end
    toc
    

    N = 100 的结果:

    Elapsed time is 0.096206 seconds.
    Elapsed time is 0.235686 seconds.
    Elapsed time is 0.154150 seconds.
    

    N = 1000 的结果:

    Elapsed time is 0.481456 seconds.
    Elapsed time is 4.534572 seconds.
    Elapsed time is 0.550606 seconds.
    

    【讨论】:

    • 您对这两者中的哪一个更快有什么看法?
    • @GregorianFunk 我不知道...另外,它可能取决于A 的大小。有时,一种解决方案对于小尺寸来说是最快的,但对于大尺寸却不是。一定要试一试!
    • @GregorianFunk 我已经做了一些测试(见编辑的答案)。第一个显然更快。 chappjc 的答案非常接近
    【解决方案2】:
    [uA,~,ic] = unique(A);    % uA(ic) == A
    mult = accumarray(ic.',1);
    

    accumarray 非常快。不幸的是,unique 在 3 个输出时变慢了。


    后期添加:

    uA = unique(A);
    mult = nonzeros(accumarray(A(:),1,[],@sum,0,true))
    

    【讨论】:

      【解决方案3】:
      S = sparse(A,1,1);
      [uA,~,mult] = find(S);
      

      我在an old Newsgroup thread 中找到了这个优雅的解决方案。

      使用benchmark of Luis MendoN = 1000 进行测试:

      Elapsed time is 0.228704 seconds. % histc
      Elapsed time is 1.838388 seconds. % bsxfun
      Elapsed time is 0.128791 seconds. % sparse
      

      (在我的机器上,accumarray 的结果是 Error: Maximum variable size allowed by the program is exceeded.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-20
        • 1970-01-01
        相关资源
        最近更新 更多