Search code examples
matlabcells

remove empty cells in MATLAB


I want to remove all empty cells at the bottom of a matlab cell array. However all code example that I found collapse the matrix to a vector, which is not what I want.

So this code

a = { 1, 2; 3, 4; [], []}
emptyCells = cellfun('isempty', a); 
a(emptyCells) = []

results in this vector

a = [1] [3] [2] [4]

But I want instead this array

a =

[1]    [2]

[3]    [4]

How would I do that?


Solution

  • If you want to delete all the rows in your cell array where all cell are empty, you can use the follwing:

    a = { 1, 2; 3, 4; [], []}
    emptyCells = cellfun('isempty', a); 
    
    a(all(emptyCells,2),:) = []
    
    a = 
        [1]    [2]
        [3]    [4]
    

    The reason it didn't work in your formulation is that if you index with an array, the output is reshaped to a vector (since there is no guarantee that entire rows or columns will be removed, and not simply individual elements somewhere).