Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect empty cells in a cell array?

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)==[]

like image 238
N.C. Rolly Avatar asked Aug 03 '10 20:08

N.C. Rolly


People also ask

How do I check if a cell array is empty in Matlab?

TF = isempty( A ) returns logical 1 ( true ) if A is empty, and logical 0 ( false ) otherwise.

How do you create an empty cell array in Matlab?

When you have data to put into a cell array, create the array using the cell array construction operator, {}. You also can use {} to create an empty 0-by-0 cell array.


1 Answers

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

like image 83
Jonas Avatar answered Sep 28 '22 11:09

Jonas