Grouping matrix rows by one column

First of all, it is very difficult for me to describe the problem really well, but I will try.

Say we have a 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 a conclusion,

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

Keep in mind that the original A is a huge matrix, and I don't want to do this with loops. I would like to use functions that use parallel processing.

+3
source share
2 answers

Here you can use accumarray :

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

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

 counts = histc(A(:,2),unique(A(:,2))); B = mat2cell(A(:,1),counts); 
+6
source

Here is an easy way to do this. It uses a loop, but should be pretty fast, because an array of B cells is pre-allocated using a reverse index trick.

 for key = fliplr(unique(A(:,2)')) ndx = A(:,2) == key; B{key} = A(ndx,1)'; end 
+1
source

Source: https://habr.com/ru/post/1489482/


All Articles