【问题标题】:break a matrix to sub-matrices with equal 2nd column without using for loop在不使用 for 循环的情况下将矩阵分解为第二列相等的子矩阵
【发布时间】:2014-11-06 11:12:46
【问题描述】:

我有一个矩阵 L,它有两列。我想找到它的子矩阵在它们的第二列上具有相同的值。我想在没有任何 for 循环的情况下使用 MATLAB 来做到这一点。 示例:

L=[1 2;3 2;4 6;5 3;7 3;1 3;2 7;9 7] 

那么子矩阵是:

[1 2;3 2] , [4 6] , [5 3;7 3;1 3] and [2 7;9 7]

【问题讨论】:

    标签: matlab


    【解决方案1】:

    您可以使用 arrayfun + unique 的组合来获得 -

    [~,~,labels] = unique(L(:,2),'stable')
    idx = arrayfun(@(x) L(labels==x,:),1:max(labels),'Uniform',0)
    

    显示输出 -

    >> celldisp(idx)
    idx{1} =
         1     2
         3     2
    idx{2} =
         4     6
    idx{3} =
         5     3
         7     3
         1     3
    idx{4} =
         2     7
         9     7
    

    【讨论】:

    • 哦,顺便说一句,我不认为 arrayfun 是矢量化/无循环解决方案!无论如何,如果您的输出没有定期成形,您就无法获得矢量化解决方案。
    【解决方案2】:

    您可以直接使用accumarray,也可以与排序数组一起使用,具体取决于您希望行的顺序是稳定的,还是子矩阵的顺序是稳定的。

    假设您希望行稳定:

    >> [L2s,inds] = sort(L(:,2));
    >> M = accumarray(L2s,inds,[],@(v){L(v,:)});
    >> M(cellfun(@isempty,M)) = [];  % remove empty cells
    >> celldisp(M)
    M{1} =
         1     2
         3     2
    M{2} =
         5     3
         7     3
         1     3
    M{3} =
         4     6
    M{4} =
         2     7
         9     7
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-12
      • 1970-01-01
      • 1970-01-01
      • 2014-05-01
      • 1970-01-01
      • 2012-06-14
      • 2019-11-21
      • 2021-11-04
      相关资源
      最近更新 更多