Grouping matrix rows in terms of one column

2019-01-20 13:38发布

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
     86 1
     98 2
     1  2
     23 2
     14 3
     15 4
     85 4]

What I want as an output is

    B{1} = [23,45,78,86]
    B{2} = [98,1,23]
    B{3} = [14]
    B{4} = [15,85]

Bear in mind that the original A is a huge matrix, and I do not wanna do this with for loops. I would like to use functions that uses parallel processing.

2条回答
Emotional °昔
2楼-- · 2019-01-20 14:20

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);
查看更多
▲ chillily
3楼-- · 2019-01-20 14:37

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
查看更多
登录 后发表回答