There are lots of alternatives.
- Input A is a vector of 1s and 0s.
- n is minimum number of 0s between 1s separate groups of 1s.
- T is a table showing the start and stop index for each consecutive group of 1s split by less than n zeros and the length of each group.
A = [0 0 0 1 1 1 0 0 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 1 1 0 1 0 1 1 0 1 0 0 0 0 1 1 1 1];
T.OnesLength = diff(find([0;A(:);0]==0))-1;
T(T.OnesLength==0,:) = [];
T.OnesStart = find(diff([0;A(:)])==1);
T.OnesStop = T.OnesStart + T.OnesLength - 1;
ZerosBetween = [T.OnesStart(2:end) - T.OnesStop(1:end-1); NaN]-1;
disp(T)
OnesLength OnesStart OnesStop
__________ _________ ________
3 4 6
3 9 11
6 18 23
2 29 30
1 32 32
2 34 35
1 37 37
4 42 45
joinGroups = ZerosBetween < n;
t = find(diff([0;joinGroups])==1);
f = find(diff([0;joinGroups])==-1);
T.remove = false(height(T),1);
T.OnesStop(t(i)) = T.OnesStop(f(i));
T.OnesLength(t(i)) = sum(T.OnesLength(t(i):f(i))) + sum(ZerosBetween(t(i):f(i)-1));
T.remove(t(i)+1:f(i)) = true;
disp(T)
OnesLength OnesStart OnesStop
__________ _________ ________
8 4 11
6 18 23
9 29 37
4 42 45
Now you can use the segment length and the start/stop indices to compute the segement centers.
Best Answer