Count the length of repeated value sets in an array?

Sorry if my question title is confusing -
For a given binary array, I'm trying to count the total length of consecutive sets of ones.
For example, x = [1 0 0 1 1 1 0 1 0 1 1 0 0 0]
should result in [1 3 1 2]
Any help is appreciated :)

Answers (3)

x = [1 0 0 1 1 1 0 1 0 1 1 0 0 0]
out=nonzeros(accumarray(nonzeros(x.*(cumsum(~x)+1)),1))
f = find(diff([false,x==1,false])~=0);
L = f(2:2:end)-f(1:2:end-1);
x = [1 0 0 1 1 1 0 1 0 1 1 0 0 0];
t = cumsum(diff([0;x(:)])==1).*x(:);
out = accumarray(t(t>0),1);
or
t = bwlabel(x(:));
out = accumarray(t(t>0),1);

Asked:

on 28 Apr 2016

Commented:

on 28 Apr 2016

Community Treasure Hunt

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

Start Hunting!