Replace empty cells with logical 0's before cell2mat in MATLAB

I have an array of empty cells and ones that I want to convert to a logical array, where the empty cells are zeros. When I use cell2mat, the empty cells are ignored, and I end up with a matrix of solely 1's, with no reference to the previous index they held. Is there a way to perform this operation without using loops?

Example code:

for n=1:5              %generate sample cell array
mycellarray{2}=[]      %remove one value for testing

Things I've tried:


which results in [1,1,1,1], not [1,0,1,1,1].

for n=1:length(mycellarray)
    if isempty(mycellarray{n})

which works, but uses loops.


If you know your cell array is only going to contain ones and [] (which represent your zeroes), you can just use the function cellfun to get a logical index of the empty cells, then negate the index vector:

mylogicalarray = ~cellfun(@isempty, mycellarray);
% Or the faster option (see comments)...
mylogicalarray = ~cellfun('isempty', mycellarray);

If your cells could still contain zero values (not just []), you could replace the empty cells with 0 by first using the function cellfun to find an index for the empty cells:

emptyIndex = cellfun('isempty', mycellarray);     % Find indices of empty cells
mycellarray(emptyIndex) = {0};                    % Fill empty cells with 0
mylogicalarray = logical(cell2mat(mycellarray));  % Convert the cell array

mycellarray( cellfun(@isempty, mycellarray) ) = {0};
mylogicalarray = logical(cell2mat(mycellarray));

Need Your Help

R's lmer cheat sheet

r mixed-model random-effects-model fixed-effects-model lme4-nlme

There's a lot of discussion going on on this forum about the proper way to specify various hierarchical models using lmer.

AngularJS passing data to $http.get request

javascript angularjs javascript-framework

I have a function which does a http POST request. The code is specified below. This works fine.