# sum only consecutive 1's in matrix

1 view (last 30 days)
C.G. on 20 Oct 2021
Commented: Matt J on 20 Oct 2021
I have a matrix of data where I want to go down each column in the matrix, and sum the occurences where 1's occur consectively. E.g. if I have
1
0
1
1
0
1
1
I want this to be recorded as 1,2,2 as the groups of 1's are separated by 0's. I want this data to be stored in a new matrix where the sum data for each column is stored in a column (in the same format as the orignal data).
Is this possible?

Image Analyst on 20 Oct 2021
This will do it:
% Read in data.
particleNotMoved = s.particleNotMoved
% Prepare a matrix to hold our output -- the run lengths.
[rows, columns] = size(particleNotMoved)
output = zeros(floor(rows/2), columns)
% Loop over all columns, getting the run lengths of each run.
for col = 1 : columns
% Use regionprops in the Image Processing Toolbox.
props = regionprops(logical(particleNotMoved(:, col)), 'Area');
% Get the run lengths for this column.
runLengths = [props.Area]';
% Insert result for this column into our output array.
output(1:numel(runLengths), col) = runLengths;
end
C.G. on 20 Oct 2021
Ok thank you

### More Answers (1)

Matt J on 20 Oct 2021
See,
Tools for Processing Consecutive Repetitions in Vectors
[~,~,runlengths]=groupLims(groupTrue(particleNotMoved),1)
##### 2 CommentsShowHide 1 older comment
Matt J on 20 Oct 2021
An easy modification.
X=particleNotMoved;
X(end+1,:)=0;
[starts,~,runlengths]=groupLims(groupTrue(X(:)),1);
[~,G]=ind2sub(size(X),starts);
result = splitapply(@(x) {x}, runlengths,G )