dividing out smaller matrices bracketed by columns of just 0's

I have a 16 high by 200 wide matrix of somewhat random 0's and 1's. I'm trying to section off smaller matrices..of columns that each contain at least one 1, which are bracketed by columns of pure 0's. So for 001101110010, assuming theres just one row, there would be 3 smaller matrices of 2, 3, and 1 columns. And then I was hoping to count all the ones in each respective matrix. Any ideas?
Thank you

1 Comment

So for this you would want the sum of the number of ones in columns 3,4 as one value, 678 as a seconf etc? This would be a good CODY problem.

Sign in to comment.

 Accepted Answer

t = any(YourMatrix,1);
fc = strfind(t, [0 1]) + 1;
lc = strfind(t, [1 0]);
Then each pair fc(K), lc(K) gives the columns to sum submatrix #K over.
You may wish to consider making the above logic more robust to take into account the possibility that a submatrix starts at the very beginning of YourMatrix or ends at the very end of YourMatrix.

1 Comment

Thank you. So how would you enable MATLAB to automatically input the fc and lc ends and sum those matrices? so that I could reproduce this and not have to manually enter it?
Thanks again, I really appreciate the help

Sign in to comment.

More Answers (1)

One of many ways:
x = [0 1 1 0 1 0 1 1 1;ones(1,9)]; %sample
dcdr = diff([0 x(1,:) 0]); %1st deriv
blow = find(dcdr==1); %low bound
bup = find(dcdr==-1)-1; %high bound
xs = sum(x); %columns sums
for ii = numel(bup):-1:1
S(ii) = sum(xs(blow(ii):bup(ii))); %each one
end

Community Treasure Hunt

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

Start Hunting!