Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Series of consecutive numbers (different lengths)

I would appreciate if someone showed me an easy way to do this. Let's say I have a vector in MATLAB like

d = [3 2 4 2 2 2 3 5 1 1 2 1 2 2 2 2 2 9 2]

I want to find the series of consecutive number "twos" and the lengths of those series.

Number twos can easily be found by x=find(d==2). But what I want is to get a vector which contains the lengths of all series of consecutive number twos, which means that my result in this case would be a vector like this:

[1 3 1 5 1].

Anyone who could help me?

like image 372
alex Avatar asked Oct 21 '11 13:10

alex


2 Answers

This seems to work:

q = diff([0 d 0] == 2);
v = find(q == -1) - find(q == 1);

gives

v =

   1   3   1   5   1

for me

like image 142
Max Avatar answered Nov 15 '22 05:11

Max


This is called run length encoding. There is a good m-file available for it at http://www.mathworks.com/matlabcentral/fileexchange/4955-rle-deencoding . This method is generally faster than the previously posted diff/find way.

tic
d_rle = rle(d==2);
d_rle{2}(d_rle{1}==1);
toc

Elapsed time is 0.002632 seconds.

tic
q = [0 diff([0 d 0] == 2)];
find(q == -1) - find(q == 1);
toc

Elapsed time is 0.003061 seconds.

like image 30
John Colby Avatar answered Nov 15 '22 06:11

John Colby