Cell of grouped elements

63 views Asked by At

I have a linked list S with S(i)=s_i and S(i) is a non-negative integer number. I want a cell C=C{0+1},...C{max(S)+1} such that C{i+1}={i_1,...,i_k}, S(i_1)=...=S(i_k)=i and k is maximal. Example:

S(1)=0,S(2)=0,S(3)=1,S(4)=2,S(5)=1,S(6)=2,S(7)=6,

Then I should get

 C{0+1}={1,2}, C{1+1}={3,5}, C{2+1}={4,6}, C{3+1}={},...C{6+1}={7}, C{7+1}={}

How can I do that as fast as possible in matlab ?

I already found

Place equal elements in cell array

However, I also need the empty sets like in C{3+1}.

How can I do that ?

1

There are 1 answers

0
Luis Mendo On BEST ANSWER

It can be done very easily with accumarray:

C = accumarray(S(:)+1, 1:numel(S), [], @(x) {sort(x.')});

Here's an alternative with bsxfun and mat2cell:

t = bsxfun(@eq, S(:), 0:max(S));
s = sum(t, 1);
t = bsxfun(@times, t, (1:numel(S)).');
C = mat2cell(nonzeros(t).', 1, s);