Count number of consecutive 1's within a block

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

Let x be the given row vector.
f = find(diff([0,x,0]==1));
p = f(1:2:end-1); % Start indices
y = f(2:2:end)-p; % Consecutive ones’ counts

7 Comments

Perfect, just saved me a lot of headaches, thank you kindly
what does the f vector contain? (p and y I understand)
The array f contains the indexes in x where the transitions 0->1 or 1->0 occur.
f alternates p (0->1) and y+p (1->0).
@Bruno Luong thank you!
I am having problems with how to convert the Accepted answer code so that the p and y vectors now start checking for 0 instead of 1.
In other words how do i change the code so:
  • p returns the indices of 1->0 transition
  • y returns the lengths of the consecutive sequences with their elements equal to 0.
I'll be grateful!
For detection of sequence of 0s
f = find(diff([1,x,1]==0));
p = f(1:2:end-1); % Start indices
y = f(2:2:end)-p; % Consecutive zeros’ counts
How would this code be adjusted to include a gap of zero for 11 in the code so that the output vector is the same length?
What does that mean? I have no idea what "include a gap of zero for 11 in the code" means. Please explain. What is a gap of zero? A zero width gap? What is that? What's eleven?

Sign in to comment.

More Answers (1)

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

1 Comment

This looks close to what I want, unfortunately I'm working with the base program without any add-ons. Thank you though!

Sign in to comment.

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!