MATLAB: How to create a conditional adding counter

counterImage Processing Toolbox

Hi. I have a matrix of 1's and 0's and I want to set a counter to search for the 1's and add them up and stop when it gets to a 0, and start again at the next 1.
For example [0;1;1;1;0;0;0;0;1;1;0;0;0;1]. I expect the counter to solve and obtain [3;2;1]. Thanks.

Best Answer

If you have the Image Processing Toolbox (type ver to check), then regionprops will compute the number of elements in each connected group of 1's for you:
m = [0;1;1;1;0;0;0;0;1;1;0;0;0;1]; % Sample data.
props = regionprops(logical(m), 'Area'); % Measure areas, put results into a structure array.
allAreas = [props.Area] % Results: allAreas = [3, 2, 1]
regionprops() is very robust and accurate and well tested.
Related Question