【问题标题】:Order of elements in cell array constructed by accumarrayaccumarray 构造的元胞数组中的元素顺序
【发布时间】:2015-01-12 05:21:44
【问题描述】:

我正在尝试做的事情:给定一个二维矩阵,获取每行中满足某些特定条件的元素的列索引。

例如,假设我的矩阵是

M = [16 2 3 13; 5 11 10 8; 9 7 6 12; 4 14 15 1]

我的条件是M>6。那么我想要的输出会是这样的

Indices = {[1 4]'; [2 3 4]'; [1 2 4]'; [2 3]';}

阅读this similar question 的答案后,我想出了使用findaccumarray 的部分解决方案:

[ix, iy] = find(M>6);
Indices = accumarray(ix,iy,[],@(iy){iy});

这几乎给出了我想要的结果——事实上,索引没问题,但它们没有按照我预期的方式排序。例如,Indices{2} = [2 4 3]' 而不是[2 3 4]',我不明白为什么。 2ix 中出现 3 次,分别位于索引 369iy 在这些索引处的对应值依次为234。究竟是什么创建了观察到的顺序?这只是随意的吗?除了事后对Indices 的每个元素进行排序之外,有没有办法强制它成为我想要的?

【问题讨论】:

    标签: matlab matrix cell-array


    【解决方案1】:

    这是解决它的一种方法 arrayfun -

    idx = arrayfun(@(x) find(M(x,:)>6),1:size(M,1),'Uni',0)
    

    显示输出celldisp(idx) -

    idx{1} =
         1     4
    idx{2} =
         2     3     4
    idx{3} =
         1     2     4
    idx{4} =
         2     3
    

    要继续使用accumarray,您可以将iysort 包装起来,以获得您想要的输出,它可能看起来不太漂亮 -

    Indices = accumarray(ix,iy,[],@(iy){sort(iy)})
    

    输出 -

    >> celldisp(Indices)
    Indices{1} =
         1
         4
    Indices{2} =
         2
         3
         4
    Indices{3} =
         1
         2
         4
    Indices{4} =
         2
         3
    

    【讨论】:

    • 漂亮!我不知道arrayfun。我仍然有点好奇为什么我尝试的方法不太奏效,但这似乎是我实际问题的完美解决方案。
    • @CurtisH。你的方法很好;只是accumarray不保持秩序
    • @CurtisH。我认为你可以用sort 包装iy。为此添加了代码。
    • @Divakar 这似乎也有效,但您的arrayfun 解决方案要快得多,至少根据我的实际数据。
    • @CurtisH。很高兴知道!我认为基于accumarray 的方法在您从它们获取数字输出时是有效的,否则在使用anonymous functions 时其性能会显着下降,但我没有数字可以证明这一点。同样的故事在bsxfun + anonymous functions 上继续,幸运的是我有数字here
    【解决方案2】:

    accumarray 不能保证保留其第二个输入的每个块的顺序(请参阅herehere)。但是,当第一个输入已经排序时,它似乎确实保留了它:

    [iy, ix] = find(M.'>6); %'// transpose and reverse outputs, to make ix sorted
    Indices = accumarray(ix,iy,[],@(iy){iy}); %// this line is the same as yours
    

    生产

    Indices{1} =
         1
         4
    
    Indices{2} =
         2
         3
         4
    
    Indices{3} =
         1
         2
         4
    
    Indices{4} =
         2
         3
    

    【讨论】:

    • 谢谢,这可以解释。我应该更仔细地阅读accumarray 文档。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多