0

I have an array. I sorted it, so I have sorted array and indeces of sorted elements in the initial array.

Fo example, from [4 5 4 4 4 4 5 4] I got [4 4 4 4 4 4 5 5] and [1 3 4 5 6 8 2 7].

How to place recieved indeces in a cell array, so that in one cell will be indeces of equal elements? For my example, it will be: {1 3 4 5 6 8}, {2 7}.

I'm searching for non-loop way to solve it.

Macaronnos
  • 647
  • 5
  • 14

1 Answers1

2

Use accumarray:

x = [4 5 4 4 4 4 5 4]; %// data

[~, ~, jj] = unique(x);
result = accumarray(jj(:), 1:numel(x), [], @(v) {v(:).'});

Or, if you need each set of indices sorted:

result = accumarray(jj(:), 1:numel(x), [], @(v) {sort(v(:)).'});
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • Got a question - Doesn't `accumarray` has looping inside it? – Divakar Mar 15 '14 at 16:11
  • @Divakar Good question. I don't know. I wouldn' be surprised if it does (in the same sense as `arrayfun` etc are loops in disguise). But it's so useful I wouldn't mind :-) – Luis Mendo Mar 15 '14 at 16:17
  • 1
    I think it has looping, but these functions are good "wrapers" to hide looping. Also, in this particular case, I don't think vectorization stands any chance. Working with cellarrays brings those limitations I think. +1 BTW – Divakar Mar 15 '14 at 16:20
  • 1
    @Divakar Thanks. Yes, cell arrays don't get on well with vectorization – Luis Mendo Mar 15 '14 at 16:35