Search code examples
matlab3dcell-array

Delete empty pages from a 3D cell array with mixed data


I have a 3D cell array with mixed data. Among them also empty cells. There are also mxn-arrays in the third dimension that have only empty cells. I want to remove those:

C(:,:,1) = {'A' 'B'; [] []; 'C' 'D'};     
C(:,:,2) = {[] []; [] []; [] []};
C(:,:,3) = {[] 1; 2 []; [] 3};

should become

C(:,:,1) = {'A' 'B'; [] []; 'C' 'D'}
C(:,:,2) = {[] 1; 2 []; [] 3}

so far I have this solution

C1 = C(:,find(~all(cellfun('isempty',C),1)));
old_m = size(C,1);
old_n = size(C1,2)/size(C,2);
reshape(C1,old_m,old_n,[]);

I mean it's basically only two lines of code. I just wonder if there's a more elegant or efficient method?

Thanks


Solution

  • This -

    C(:,:,~all(all(cellfun('isempty',C),1),2))
    

    Or this -

    C(:,:,any(any(~cellfun('isempty',C),1),2))