18

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{n}=1;
end
mycellarray{2}=[]      %remove one value for testing

Things I've tried:

mylogicalarray=logical(cell2mat(mycellarray));

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

for n=1:length(mycellarray)
    if isempty(mycellarray{n})
       mycellarray{n}=0;
    end
end
mylogicalarray=logical(cell2mat(mycellarray));

which works, but uses loops.

niton
  • 8,771
  • 21
  • 32
  • 52
Doresoom
  • 7,398
  • 14
  • 47
  • 61

2 Answers2

30

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
gnovice
  • 125,304
  • 15
  • 256
  • 359
  • 11
    Calling `cellfun('isempty',mycellarray)` is much faster than the function handle; `isempty()` is one of several functions enjoying massive speed increases when named explicitly in the `cellfun()` call. – reve_etrange Mar 17 '11 at 03:49
  • What is the purpose of the `~` in front of `cellfun`? – Chad Apr 25 '13 at 13:07
  • Ah, `~` is the logical operator not. – Chad Apr 25 '13 at 13:11
  • timings on calling cellfun('isempty',mycellarray) vs cellfun(@isempty,mycellarray) for 367x367 sized cells (on a regular laptop): 'isempty': 0.002032 @isempty: 0.083621 Thx for the tip strange_dreams! – Steve Heim Mar 20 '14 at 11:48
8
mycellarray( cellfun(@isempty, mycellarray) ) = {0};
mylogicalarray = logical(cell2mat(mycellarray));
Amro
  • 123,847
  • 25
  • 243
  • 454