In Matlab, How to eliminate empty columns from the cell array?

5.3k views Asked by At

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 ?

2

There are 2 answers

2
Luis Mendo On BEST ANSWER

Let's consider the following cell array. Its second column consists only of [], so it should be removed.

>> c = {1 , [], 'a'; 2, [], []; 3, [], 'bc'}
c = 
    [1]    []    'a' 
    [2]    []      []
    [3]    []    'bc'

You can compute a logical index to tell which columns should be kept and then use it to obtain the result:

>> keep = any(~cellfun('isempty',c), 1);  %// keep columns that don't only contain []
keep =
     1     0     1                        %// column 2 should be removed
>>  result = c(:,keep)
result = 
    [1]    'a' 
    [2]      []
    [3]    'bc'

How it works:

  1. cellfun('isempty' ,c) is a matrix the same size as c. It contains 1 at entry (m,n) if and only if c{m,n} is empty.
  2. ~cellfun('isempty' ,c) is the logical negation of the above, so it contains 1 where c is not empty.
  3. any(~cellfun('isempty' ,c), 1) applies any to each column of the above. So it's a row vector such that its m-th entry equals 1 if any of the cells of c in that column are non-empty, and 0 otherwise.
  4. The above is used as a logical index to select the desired columns of c.
0
zeeMonkeez 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]