Info

This question is closed. Reopen it to edit or answer.

How to give index to each replicated number?

1 view (last 30 days)
Qingfang Liu
Qingfang Liu on 7 May 2019
Closed: MATLAB Answer Bot on 20 Aug 2021
For example, when I have a=[1,1,1,1,3,3,4,4,4], I would like the output to be b=[1,2,3,4,1,2,1,2,3].
  2 Comments
Matt J
Matt J on 7 May 2019
Edited: Matt J on 7 May 2019
What if a number's repetitions are interrupted like in the following,
a=[1,1,1,1, 3,3, 1,1]
Should the result be
b = [1,2,3,4, 1,2, 5,6]

Answers (2)

Matt J
Matt J on 7 May 2019
Edited: Matt J on 7 May 2019
G=cumsum(diff([0,a])~=0);
b=cell2mat(splitapply(@(g){1:numel(g)}, G,G));

Matt J
Matt J on 7 May 2019
Edited: Matt J on 7 May 2019
In that case,
S=sparse( 1:numel(a), findgroups(a), 1);
S(S>0)=nonzeros( cumsum(sort(S)) );
b=full(sum(S,2)).';

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!