Search code examples
arraysmatlabsortingcell-array

Place equal elements in cell array


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.


Solution

  • 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(:)).'});