Matlab独特的细胞组合

A D*_*Doe 3 matlab list cell

我有一个列表如下:

A= {[1 2], [2 1], [2 1 3],[3 4],[4 3]}
Run Code Online (Sandbox Code Playgroud)

我需要简化矩阵.例如,[3 4][4 3]形成相同的组合,其中只有一个就足够了.此外,[1 2][2 1]是相同的组合,所以我应该留下

newA= {[1 2],[2 1 3],[3 4]}
Run Code Online (Sandbox Code Playgroud)

我怎么做?

Lui*_*ndo 5

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

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);
Run Code Online (Sandbox Code Playgroud)


exc*_*aza 5

一种方法是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);
Run Code Online (Sandbox Code Playgroud)

注1:A由于unique处理单元格数组,我不得不制作一个相当于字符串的虚拟数组.unique只能处理字符串/字符向量的单元格数组,因此我们必须进行一些操作才能获得所需的输出.

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

  • 好主意,转换为字符串!您可以组合为`tmp = cellfun(@(x)num2str(sort(x)),A,'UniformOutput',false)` (2认同)