tags:

views:

187

answers:

2

I have a simple question. How do I detect empty cells in a cell array? I know the command to eliminate 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)==[]

+4  A: 

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
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
A: 

The problem should have been treated here already, you can try this approach:

http://stackoverflow.com/questions/2624016/replace-empty-cells-with-logical-0s-before-cell2mat-in-matlab

private_meta

related questions