MATLAB: Count 1’s in binary

binarycount 1's

Hi,
This is what i want… I have a binary array
001111000000011100000000011111
from here i have to count the number 1 in such way
result: 0,4,0,3,0,5…. how to get this?

Best Answer

If you have the Image Processing Toolbox, it's just two real lines of code, a call to regionprops and a line to extract the lengths from what regionprops returns.
% Create sample binary data.
binaryArray = [0 0 1 1 1 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1]
% Measure lengths of stretches of 1's.
measurements = regionprops(logical(binaryArray), 'Area');
% Convert from structure to simple array of lengths.
allLengths = [measurements.Area]
% If you want 0's in between for some reason:
out = zeros(1, 2*length(allLengths)+1);
out(2:2:end) = allLengths
5000 numbers is no problem. This code can handle millions of them.