Let vec
be a row vector (1-by-n
) of zeros and ones, then you can use the following code
rl = ( find( vec ~= [vec(2:end), vec(end)+1] ) );
data = vec( rl );
rl(2:end) = rl(2:end) - rl(1:end-1);
rl
will give you the number of consecutive zeros and ones, while data
will tell you for each block if it is zero or one.
This question is closely related to run length coding.
Demo:
vec = [1 1 1 1 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1];
rl = ( find( vec ~= [vec(2:end), vec(end)+1] ) );
data = vec( rl ),
rl(2:end) = rl(2:end) - rl(1:end-1),
data =
1 0 1 0 1
rl =
4 3 2 14 8
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…