Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

New to MATLAB?

Count the "areas" of zeros and the "areas" of ones in a vector?

Asked by Giorgos Papakonstantinou on 21 Jun 2013

I have a vector:

a=[0 1 1 1 1 1 1 0 0 1 1 1 1 1 0 0 1 1 1 0 1 ];

in which I would like to count the "areas" of zeros and the "areas" of ones. In the example above I have

4 areas of zeros and 4 areas of ones. Thank you!

0 Comments

Products

No products are associated with this question.

3 Answers

Answer by Andrei Bobrov

Andrei Bobrov (view profile)

on 21 Jun 2013
Accepted answer
a=[0 1 1 1 1 1 1 0 0 1 1 1 1 1 0 0 1 1 1 0 1 ];
lc = [true;diff(a(:))~=0];
x = a(lc);
zerosareas = sum(~x);
onesareas = sum(x);

1 Comment

Andrei Bobrov

Andrei Bobrov (view profile)

Answer by Jan Simon

Jan Simon (view profile)

on 21 Jun 2013

Another approach which might be faster for large data sets: FEX: RunLength:

a = [0 1 1 1 1 1 1 0 0 1 1 1 1 1 0 0 1 1 1 0 1 ];
b = RunLength(a);
nZero = sum(b == 0);
nOne  = length(b) - nZero;  % Or: sum(b == 1)

2 Comments

Jan Simon

Jan Simon (view profile)

on 22 Jun 2013

For 100'000 elements, the RunLength approach is twice as fast as the DIFF method. But as long as both methods need only some milliseconds, this might not really matter.

Jan Simon

Jan Simon (view profile)

Answer by Image Analyst

Image Analyst (view profile)

on 23 Jun 2013

I know you already accepted an answer, but if you have the Image Processing Toolbox there is a straightforward one-liner solution to get either of those numbers:

a=[0 1 1 1 1 1 1 0 0 1 1 1 1 1 0 0 1 1 1 0 1];
[~, numberOf1Regions] = bwlabel(a)      % Get # of "1" regions.
[~, numberOf0Regions] = bwlabel(~a)     % Get # of "0" regions.

0 Comments

Image Analyst

Image Analyst (view profile)

Contact us