MATLAB: Grouping of sub arrays

groupingsub-arrays

Dear Matlab community,
This is a toy example to explain my question:
x=[1 1 2 3 3 1 0 4 4 4 1 1 1 1 5 5 0 1 3 3 3 3 1 4 4 4 0 0 1 1 5 6];
I have used the following function to define regions of interest:
[Groups, NumberOfGroups] = bwlabel(x >= 3);
>>NumberOfGroups = 6
>> Groups = [0 0 0 1 1 0 0 2 2 2 0 0 0 0 3 3 0 0 4 4 4 4 0 5 5 5 0 0 0 0 6 6]
I got groups as follows: {(1,1), (2,2,2) (3,3) ,…}
Now, if the end of group 1 is only 2 samples or less from the start of group 2, then the new group will start from the start of group 1 to the end of group 2. The suggested solution must look at all consecutive groups to see if, for example, group 3 was two samples of less from group 2, then the new group will start from the beginning of group 1 to the end of group 3.
I have attached an illustarative image. In this image, the bwlabel resulted in 44 groups, while I want only 6 groups (all near by sub-groups must go to one big group).
Best regards,

Best Answer

Are you looking for something like this
x=[1 1 2 3 3 1 0 4 4 4 1 1 1 1 5 5 0 1 3 3 3 3 1 4 4 4 0 0 1 1 5 6];
Groups = bwlabel(x >= 3);
cc = bwconncomp(Groups==0);
idx = cellfun(@numel, cc.PixelIdxList)<=2;
idx = cell2mat(cc.PixelIdxList(idx).');
Groups(idx) = nan;
Groups = fillmissing(Groups, 'next')
Result
>> Groups
Groups =
Columns 1 through 16
0 0 0 1 1 2 2 2 2 2 0 0 0 0 3 3
Columns 17 through 32
4 4 4 4 4 4 5 5 5 5 0 0 0 0 6 6
or perhaps you also want to do this at the end
Groups = bwlabel(Groups>0)
Result
>> Groups
Groups =
Columns 1 through 16
0 0 0 1 1 1 1 1 1 1 0 0 0 0 2 2
Columns 17 through 32
2 2 2 2 2 2 2 2 2 2 0 0 0 0 3 3