HappyPy
HappyPy

Reputation: 10697

count adjacent elements in vector with repetitions - matlab

v = [1,1,1,2,3,3,4,4,4,4,2,3,3,3,1,1]

I'm looking for a way to count adjacent elements in vector c without loosing the repetitions. This is the desired output:

c = 
      3  1  2  4  1  3  2 

Upvotes: 1

Views: 100

Answers (2)

Adam
Adam

Reputation: 2777

Answer from Mathworks

% code
v = [1,1,1,2,3,3,4,4,4,4,2,3,3,3,1,1];
c  = diff([0 find(diff(v)) numel(v)])

% output
c = [3  1  2  4  1  3  2]

Upvotes: 1

L. Scott Johnson
L. Scott Johnson

Reputation: 4412

Use diff() to spot the change points, then get the indexes of those points.

id = diff(v)==0; 
idx = strfind([id 0], 0);
c = [idx(1) diff(idx)]

Output:

c =

     3     1     2     4     1     3     2

Upvotes: 2

Related Questions