Count number of consecutive 1's within a block

25 views (last 30 days)
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

Roger Stafford
Roger Stafford on 19 Dec 2016
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
Tomos Winstanley
Tomos Winstanley on 16 Jan 2021
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?
Image Analyst
Image Analyst on 17 Jan 2021
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)

Image Analyst
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
  1 Comment
DoyleDk
DoyleDk on 19 Dec 2016
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 Mathematics 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!