Grouping matrix rows in terms of one column

前端 未结 2 697
无人共我
无人共我 2020-12-11 22:43

First of all it is really hard for me to describe the problem really good but I\'ll try.

Say that we have matrix A

A = [23 1;
     45 1
     78 1
            


        
相关标签:
2条回答
  • 2020-12-11 23:19

    You could use accumarray here:

    B = accumarray(A(:,2),A(:,1),[],@(x){x},{});
    

    If you know that A is sorted, and that there is no missing entry from the second column, you can also use mat2cell:

    counts = histc(A(:,2),unique(A(:,2)));
    B = mat2cell(A(:,1),counts);
    
    0 讨论(0)
  • 2020-12-11 23:26

    Here's a simple way to do it. It uses a loop, but should be pretty quick because the cell array B is pre-allocated using the reverse index trick.

    for key = fliplr(unique(A(:,2)'))
        ndx = A(:,2) == key;
        B{key} = A(ndx,1)';
    end
    
    0 讨论(0)
提交回复
热议问题