【问题标题】:Reordering a vector in Matlab?在 Matlab 中重新排序向量?
【发布时间】:2015-04-23 08:05:55
【问题描述】:

我在 Matlab B 中有一个维度为 nx1 的向量,其中包含按特定顺序从 1n 的整数,例如n=6 B=(2;4;5;1;6;3)

我有一个维度为mx1m>1 的向量A,其中包含按升序排列的相同整数,每个整数重复任意次数,例如m=13A=(1;1;1;2;3;3;3;4;5;5;5;5;6)

我想得到维度为mx1C,其中A 中的整数按照B 中的顺序重新排序。在示例中,C=(2;4;5;5;5;5;1;1;1;6;3;3;3)

【问题讨论】:

    标签: arrays matlab


    【解决方案1】:

    ismembersort 的一种方法-

    [~,idx] = ismember(A,B)
    [~,sorted_idx] = sort(idx)
    C = B(idx(sorted_idx))
    

    如果你喜欢单行,那么另一个使用bsxfun -

    C = B(nonzeros(bsxfun(@times,bsxfun(@eq,A,B.'),1:numel(B))))
    

    【讨论】:

      【解决方案2】:

      这只需要一个sort 和索引:

      ind = 1:numel(B);
      ind(B) = ind;
      C = B(sort(ind(A)));
      

      【讨论】:

        【解决方案3】:

        使用repelemaccumarrayunique的另一种方法

        B=[2;4;5;1;6;3];
        A=[1;1;1;2;3;3;3;4;5;5;5;5;6];
        
        counts = accumarray(A,A)./unique(A);
        repelem(B,counts(B));
        
        %// or as suggested by Divakar 
        %// counts = accumarray(A,1);
        %// repelem(B,counts(B));
        

        PS:repelem 是在 R2015a 中引入的。如果您使用的是旧版本,请参考here

        【讨论】:

        • 如果 OP 无法访问 repelem 的 2015a,请将其链接到 this one
        • @Divakar 不是吗?即使我使用的是 R2014a,我也没有测试最后一行 LOL。
        • 想想,你可以分两步搞定:counts = accumarray(A,1); C= repelem(B,counts(B))
        • @Divakar,谢谢.. 刚刚注意到 iB 是相同的手掌
        【解决方案4】:

        使用hist 的另一种解决方案,但带有循环和扩展内存:(

        y = hist(A, max(A))
        reps = y(B);
        C = [];
        for nn = 1:numel(reps)
            C = [C; repmat(B(nn), reps(nn), 1)];
        end
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-10-24
          • 2015-09-01
          • 2017-09-19
          • 1970-01-01
          • 2021-06-29
          相关资源
          最近更新 更多