Monday, July 27, 2009

Matlab: grouping values according to ID

See also this post.

Q:

If we have n x 2 matrix x:

x = [11 19; 11 29; 10 34; 7 189; 6 123; 11 18; 21 182; 3 171; 6 145; 7 111]


Where the first column specifies the group ID and we want to break up the 2nd column into a cell array according to the grouping ID.

The desired output is:

c = {[171]; [145; 123]; [189; 111]; [34]; [18; 29; 19]; [182]}



A:

[u,dump,g] = unique(x(:,1))
c = accumarray(g,x(:,2),[length(u),1],@(x){x})

No comments: