Search code examples
matlabcell-array

How can I group adjacent not-empty cells?


I have a 4x4 cell array C, which

C= {

[1] [3] [6] [ ]; 

[2] [ ] [ ] [8];  

[ ] [4] [ ] [9]; 

[ ] [5] [7] [ ]}

I want to generate a new cell array D which give me

D = {[1;2], [3], [4;5],[6],[7],[8;9]}

basically I want to 1. combine the adjacent non empty cell in each column vertically and 2. output the new cell array D contains the result.


Solution

  • You can use this. I've used bwlabel from the imaging toolkit:

    C= {                   ...
    [1] [3] [6] [ ];       ...
    [2] [ ] [ ] [8];       ...
    [ ] [4] [ ] [9];       ...
    [ ] [5] [7] [ ]};
    
    lenf = @(X)~isempty(X);
    lens = cellfun(lenf, C);
    

    lens is now a logical array indicating if any slot in C is empty or not. Now we can construct D by treating each column in lens as a 1 x whatever binary image, and seek regions using bwlabel(). Finally we put the regions into D.

    sum = 0;
    for k = 1:size(lens,2)
        [L,num] = bwlabel(lens(:,k), 4);
        for idx = 1:num
            D{idx+sum} = cat(1, C{L==idx, k});
        end
        sum = sum + num;
    end