Count the length of repeated value sets in an array?
Show older comments
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)
Azzi Abdelmalek
on 28 Apr 2016
Edited: Azzi Abdelmalek
on 28 Apr 2016
x = [1 0 0 1 1 1 0 1 0 1 1 0 0 0]
out=nonzeros(accumarray(nonzeros(x.*(cumsum(~x)+1)),1))
Andrei Bobrov
on 28 Apr 2016
Edited: Andrei Bobrov
on 28 Apr 2016
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);
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!