8

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?

Jonas
  • 73,844
  • 10
  • 134
  • 175
Matthias Pospiech
  • 2,714
  • 15
  • 46
  • 65

4 Answers4

17

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).

Jonas
  • 73,844
  • 10
  • 134
  • 175
1

There is a function that generalizes the removing specific row/columns from a cell, which is called fun_removecellrowcols. Due to the removal, cell dimensions are resized.

1

This works for me:

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

but I'm not sure if it will be general enough for you - will you always have complete rows of empty cells at the bottom of your array?

Max
  • 2,085
  • 3
  • 16
  • 18
  • Currently yes, but in general I can no be sure. I was also thinking of using reshape, but in the end I used a simple search for the last row with is not empty, because I find the code you posted too complex or the acutal task. – Matthias Pospiech Mar 14 '12 at 12:20
0

A simpler solution very specific to your problem is to convert the cell directly into a matrix:

cleanedA = cell2mat(a);

It converts to a normal matrix, and while doing this it removes the empty cells.

Then, of course, you can reconvert it to a cell array with the following command:

a = mat2cell(cleanedA, [1 1], [1 1])

Its not generic, but for the example posted it is the simplest solution I can think of.

Castilho
  • 3,097
  • 14
  • 15