36

How do I detect empty cells in a cell array? I know the command to remove the empty cell is a(1) = [], but I can't seem to get MATLAB to automatically detect which cells are empty.

Background: I preallocated a cell array using a=cell(1,53). Then I used if exist(filename(i)) and textscan to check for a file, and read it in. As a result, when the filename(i) does not exist, an empty cell results and we move onto the next file.

When I'm finished reading in all the files, I would like to delete the empty cells of a. I tried if a(i)==[]

Amro
  • 123,847
  • 25
  • 243
  • 454
N.C. Rolly
  • 363
  • 1
  • 3
  • 4

2 Answers2

61

Use CELLFUN

%# find empty cells
emptyCells = cellfun(@isempty,a);
%# remove empty cells
a(emptyCells) = [];

Note: a(i)==[] won't work. If you want to know whether the the i-th cell is empty, you have to use curly brackets to access the content of the cell. Also, ==[] evaluates to empty, instead of true/false, so you should use the command isempty instead. In short: a(i)==[] should be rewritten as isempty(a{i}).

Jonas
  • 74,690
  • 10
  • 137
  • 177
  • 17
    for a slight improvement in speed use `emptyCells = cellfun('isempty', a);` ... `cellfun` has an internal `switch` statement which checks to see whether the string is one of a handful of functions which it can do a "magic" speed increase with ... This is described here: http://undocumentedmatlab.com/blog/cellfun-undocumented-performance-boost/ – JudoWill Aug 04 '10 at 15:18
  • +1 for specifying how to delete the empty cells!this leaves you with a cell array containing only the non-empty entries! – Matteo Jun 09 '14 at 19:12
  • Ten years later and `'isempty'` is *still* 70x faster than `@isempty`. – Chuck Aug 03 '19 at 22:26
0

All above mentioned answers are incorrect, because in my case when i used them, they removed empty cells and then all elements of my cell array situated in a row manner instead of preserving their actual shape. In fact after using this kind of approach your cell array elements tend to be a row cell vector.

I have found this approach which works correctly in my case.

source : https://groups.google.com/forum/#!topic/comp.softsys.matlab/p3NX0fI6u90

approach:

myCellARRAY(all(cellfun(@isempty,myCellARRAY),2), : ) = [];
Robert
  • 5,278
  • 43
  • 65
  • 115