Alex Shtoff
Alex Shtoff

Reputation: 2640

Grouping array elements

I have the following MATLAB code

out = cell(max(A), 1);
for i = 1:numel(out)
    out{i} = find(A == i);
end

in which A contains all entries in 1:max(A), with a different order and possible repetitions. At the end of the code fragment out{i} contains the indices where i appears in A. The question is - is it possible to "vectorize" the above, instead of doing a loop? I believe it can be done with accumarray but I cannot see exactly how.

Upvotes: 0

Views: 49

Answers (1)

Alex Shtoff
Alex Shtoff

Reputation: 2640

It seems I came up with the answer

out = accumarray(A, 1:max(A), [], @(x) {x})

Upvotes: 2

Related Questions