Search code examples
arraysmatlabvector

increment occurrences of repeated elements by one - matlab


v = [1,2,1,1,1,2,2]

1 and 2 are my two groups. I'm trying to increment each group by 1 every time there is a repetition

The desired result:

v2 = 
    1  1  2  3  4  2  3

I tried the functions cumsum and movsum with splitapply, but nothing has worked so far


Solution

  • I am using different values of v for more clarity:

    v = [10, 20, 10, 10, 10, 20, 20];
    
    • Memory-efficient solution, with a loop over the unique values of v:

      [a, ~, c] = unique(v);
      v2 = zeros(size(v));
      for k = 1:numel(a)
          ind = c==k;
          v2(ind) = 1:sum(ind); 
      end
      
    • Memory-inefficient (it builds an intermediate N×N matrix, N = numel(v)), but simpler:

      v2 = sum(triu(v==v.'));
      
    • Another approach, probably memory-efficient too:

      s = sparse(c, 1:numel(c), 1);
      v2 = nonzeros(s.*cumsum(s, 2)).';