Count number of consecutive 1's within a block
Show older comments
If x= 0 0 0 0 1 1 1 1 0 1 1 1 0 1 1 0 1 0 then the intended output would be y=4 3 2 1. It would also be useful if I had someway of knowing when each group started, as in 4 having begun at the 5th point and 3 at the 10th etc.
Many thanks in advance!
Accepted Answer
More Answers (1)
Image Analyst
on 19 Dec 2016
Use regionprops():
x= [0 0 0 0 1 1 1 1 0 1 1 1 0 1 1 0 1 0]
% Label each separate region.
[labeledX, numRegions] = bwlabel(x)
% Get lengths of each region
props = regionprops(labeledX, 'Area', 'PixelList');
regionLengths = [props.Area]
for k = 1 : numRegions
fprintf('Region #%d is %d elements long and starts at element #%d\n',...
k, regionLengths(k), props(k).PixelList(1));
end
You'll see in the command window:
regionLengths =
4 3 2 1
Region #1 is 4 elements long and starts at element #5
Region #2 is 3 elements long and starts at element #10
Region #3 is 2 elements long and starts at element #14
Region #4 is 1 elements long and starts at element #17
Categories
Find more on Get Started with MATLAB in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!