【问题标题】:Matlab unique cell combinationsMatlab 独特的单元格组合
【发布时间】:2017-11-15 00:42:52
【问题描述】:

我有一个清单如下:

A= {[1 2], [2 1], [2 1 3],[3 4],[4 3]}

我需要简化矩阵。比如[3 4]和[4 3]组成同一个组合,只要其中一个就够了。另外,[1 2] 和 [2 1] 是相同的组合,所以我应该留下

newA= {[1 2],[2 1 3],[3 4]}

我该怎么做?

【问题讨论】:

    标签: matlab list cell


    【解决方案1】:

    一种方法是sort 的值并使用unique:

    A = {[1 2], [2 1], [2 1 3],[3 4],[4 3]};
    
    tmp = cellfun(@sort, A, 'UniformOutput', false);
    tmp = cellfun(@num2str, tmp, 'UniformOutput', false);
    [~, idx] = unique(tmp);
    
    newA = A(idx);
    

    请注意 1,由于 unique 对单元格数组的处理,我必须制作一个等效于 A 的字符串的虚拟数组。 unique 只能处理字符串/字符向量的元胞数组,因此我们必须进行一些操作才能获得所需的输出。

    注意 2,cellfun 几乎总是比显式循环慢,但为了简洁起见,我在这里使用它。

    【讨论】:

    • 好主意,转换成字符串!你可以合并为tmp = cellfun(@(x) num2str(sort(x)), A, 'UniformOutput', false)
    【解决方案2】:

    最有效的方法大概是对每个向量进行排序,并使用如下两个嵌套循环:

    As = cellfun(@sort, A, 'UniformOutput', false); % sort each vector
    remove = false(size(A)); % initiallize. Entries to be removed will be marked true
    for ii = 1:numel(A)
        for jj = ii+1:numel(A)
            remove(jj) = remove(jj) || isequal(As{jj}, A{ii}); % short-circuit OR
        end
    end
    result = A(~remove);
    

    【讨论】:

      【解决方案3】:

      这是使用accumarray的解决方案:

      n = cellfun(@numel,A);
      C=accumarray(n(:),1:numel(A),[],@(x){num2cell(unique(sort(vertcat(A{x}),2),'rows'),2)});
      result = vertcat(C{~cellfun(@isempty,C)})
      

      我在 Octave 中使用以下数据测试了 3 个建议的答案:

      A=arrayfun(@(x){randi([1 10],1,randi([1 10000]))},1:50);
      

      结果如下:

      ======NUM2STR=======:
      Elapsed time is 1.13129 seconds.
      ======FOR LOOP=======:
      Elapsed time is 0.237398 seconds.
      ======ACCUMARRAY=======:
      Elapsed time is 0.036804 seconds.
      

      有以下数据:

      A=arrayfun(@(x){randi([1 3],1,randi([1 5]))},1:500);    
      

      结果:

      ======NUM2STR=======:
      Elapsed time is 0.384026 seconds.
      ======FOR LOOP=======:
      Elapsed time is 10.9931 seconds.
      ======ACCUMARRAY=======:
      Elapsed time is 0.0271118 seconds.
      

      Online Demo

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多