So in 3 X 18 cell array, 7 columns are empty and I need a new cell array that's 3 X 11. Any suggestions without going for looping ?
In Matlab, How to eliminate empty columns from the cell array?
5.3k views Asked by miprakas At
        	2
        	
        There are 2 answers
0
                
                        
                            
                        
                        
                            On
                            
                            
                                                    
                    
                Use cellfun to detect elements, then from that find columns with empty elements and delete those:
cellarray(:, any(cellfun(@isempty, cellarray), 1)) = [];
If instead you'd like to keep columns with at least one non-empty element, use all instead of any.
For example:
>> cellarray = {1 2 ,[], 4;[], 5, [], 3}
    [1]    [2]    []    [4]
     []    [5]    []    [3]
>> cellarray(:,any(cellfun(@isempty, cellarray), 1))=[]
cellarray = 
    [2]    [4]
    [5]    [3]
                        
Let's consider the following cell array. Its second column consists only of
[], so it should be removed.You can compute a logical index to tell which columns should be kept and then use it to obtain the result:
How it works:
cellfun('isempty' ,c)is a matrix the same size asc. It contains1at entry(m,n)if and only ifc{m,n}is empty.~cellfun('isempty' ,c)is the logical negation of the above, so it contains1wherecis not empty.any(~cellfun('isempty' ,c), 1)appliesanyto each column of the above. So it's a row vector such that itsm-th entry equals1if any of the cells ofcin that column are non-empty, and0otherwise.c.